You can download this code by clicking the button below.
This code is now available for download.
This function is used to query user information from the database according to the user ID. It first connects to the database, then executes an SQL query, and finally returns the query result.
Technology Stack : PyMySQL, DictCursor
Code Type : Database query
Code Difficulty : Intermediate
def select_random_user(user_id):
import pymysql
from pymysql.cursors import DictCursor
connection = pymysql.connect(host='localhost',
user='yourusername',
password='yourpassword',
db='yourdatabase',
charset='utf8mb4',
cursorclass=DictCursor)
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM users WHERE id = %s"
cursor.execute(sql, (user_id,))
result = cursor.fetchone()
return result
finally:
connection.close()