You can download this code by clicking the button below.
This code is now available for download.
This function connects to the database and randomly selects a customer from the `customers` table. It first creates a cursor object, then executes a query to select a randomly chosen customer ID, and finally closes the cursor and returns the query result.
Technology Stack : PyMySQL
Code Type : Database query
Code Difficulty : Intermediate
import pymysql
import random
def select_random_customer(db_connection):
cursor = db_connection.cursor()
query = "SELECT * FROM customers WHERE customer_id = %s"
customer_id = random.randint(1, 100)
cursor.execute(query, (customer_id,))
customer = cursor.fetchone()
cursor.close()
return customer