To interface with a MySQL database from a Python application, follow these steps:
-
Install the MySQL Connector: First, insure you have the MySQL Connector/Python installed. This is the official library from MySQL for Python database interactions. Install it using pip:
pip install mysql-connector-python -
Import the Connector Module: Begin your Python script by importing the necessary module:
import mysql.connector -
Connect to the MySQL Server: Utilize the
mysql.connector.connect()functoin to establish a connection. You'll need to provide the servre's hostname, your username, password, and optionally, the specific database name.try: db_connection = mysql.connector.connect( host='localhost', user='db_user', password='db_password', database='my_database' # Specify if targeting a particular database ) print("Successfully connected to MySQL!") # Proceed with database operations here... except mysql.connector.Error as db_err: print(f"Error connecting to MySQL: {db_err}") finally: if 'db_connection' in locals() and db_connection.is_connected(): db_connection.close() print("MySQL connection closed.") -
Execute SQL Commands: Once connected, use the
db_connectionobject to execute SQL queries and commands. A cursor object is typically used for this purpose:# Create a cursor object to execute SQL statements db_cursor = db_connection.cursor() # Example: Fetching data db_cursor.execute("SELECT id, name FROM customers") results = db_cursor.fetchall() for record in results: print(record) # Example: Inserting data insert_query = "INSERT INTO products (product_name, price) VALUES (%s, %s)" product_data = ('Gadget', 99.99) db_cursor.execute(insert_query, product_data) # Commit changes for data modification statements db_connection.commit() # Close the cursor db_cursor.close() -
Close the Connection: Always ensure the database connection is closed after all operations are completed to free up resources.
db_connection.close()
Remember to replace placeholder connection details with your actual MySQL server credentials and database name.