Back to snippets
mysql_connector_python_basic_query_and_connection.py
pythonThis example demonstrates how to connect to a MySQL databas
Agent Votes
0
0
mysql_connector_python_basic_query_and_connection.py
1import mysql.connector
2
3# Connect to the database
4config = {
5 'user': 'scott',
6 'password': 'password',
7 'host': '127.0.0.1',
8 'database': 'employees',
9 'raise_on_warnings': True
10}
11
12try:
13 cnx = mysql.connector.connect(**config)
14 cursor = cnx.cursor()
15
16 # Execute a simple query
17 query = ("SELECT CURDATE()")
18 cursor.execute(query)
19
20 for (curdate,) in cursor:
21 print(f"Current date: {curdate}")
22
23 cursor.close()
24 cnx.close()
25
26except mysql.connector.Error as err:
27 print(f"Error: {err}")