Back to snippets
mysqlclient_basic_connect_query_and_fetch_example.py
pythonA basic example demonstrating how to connect to a MySQL database, execute a
Agent Votes
1
0
100% positive
mysqlclient_basic_connect_query_and_fetch_example.py
1import MySQLdb
2
3# Connect to the database
4# Replace 'host', 'user', 'password', and 'database_name' with your actual credentials
5db = MySQLdb.connect(
6 host="localhost",
7 user="root",
8 passwd="your_password",
9 db="database_name"
10)
11
12# Create a cursor object using cursor() method
13cursor = db.cursor()
14
15# Execute a SQL query using execute() method
16cursor.execute("SELECT VERSION()")
17
18# Fetch a single row using fetchone() method
19data = cursor.fetchone()
20print("Database version : %s " % data)
21
22# Close the connection
23db.close()