Python Interface with SQL Databases using mysql-connector
Python can interact with SQL databases using various libraries. One of the popular libraries
for interacting with MySQL databases is mysql-connector. This library allows Python to
execute SQL queries, fetch data, and manipulate databases directly from a Python program.
1. Installation of mysql-connector
To interface Python with a MySQL database, you first need to install the mysql-connector
library. This can be done using pip:
1. pip install mysql-connector-python
2. Connecting to the MySQL Database
Once the mysql-connector library is installed, you can connect to a MySQL database. For
this, you need:
Host (usually "localhost" for a local server)
Username
Password
Database name (optional)
1. import mysql.connector
2.
3. # Establishing the connection
4. conn = mysql.connector.connect(
5. host="localhost",
6. user="your_username",
7. password="your_password",
8. database="your_database"
9. )
10.
11. # Checking if the connection was successful
12. if conn.is_connected():
13. print("Connected to the database")
3. Creating a Cursor
A cursor object is used to execute SQL queries. Once connected, you create a cursor to send
commands and fetch results from the database.
1. # Creating a cursor object
2. cursor = conn.cursor()
4. Executing SQL Queries
You can use the cursor.execute() method to run SQL queries. Let’s look at a few
examples:
Creating a Table
1. # SQL command to create a table
2. create_table_query = """
3. CREATE TABLE students (
4. id INT AUTO_INCREMENT PRIMARY KEY,
5. name VARCHAR(100),
6. age INT,
7. grade VARCHAR(10)
8. )
9. """
10.
11. # Executing the query
12. cursor.execute(create_table_query)
Inserting Data
1. # SQL command to insert data
2. insert_data_query = """
3. INSERT INTO students (name, age, grade)
4. VALUES (%s, %s, %s)
5. """
6. # Data to be inserted
7. data = ("John Doe", 16, "10th")
8.
9. # Executing the query
10. cursor.execute(insert_data_query, data)
11.
12. # Committing the changes to the database
13. conn.commit()
Fetching Data
1. # SQL command to fetch data
2. fetch_data_query = "SELECT * FROM students"
3.
4. # Executing the query
5. cursor.execute(fetch_data_query)
6.
7. # Fetching all the rows
8. result = cursor.fetchall()
9.
10. # Printing the results
11. for row in result:
12. print(row)
Updating Data
1. # SQL command to update data
2. update_query = "UPDATE students SET age = %s WHERE name = %s"
3. data = (17, "John Doe")
4.
5. # Executing the query
6. cursor.execute(update_query, data)
7.
8. # Committing the changes
9. conn.commit()
Deleting Data
1. # SQL command to delete data
2. delete_query = "DELETE FROM students WHERE name = %s"
3. data = ("John Doe",)
4.
5. # Executing the query
6. cursor.execute(delete_query, data)
7.
8. # Committing the changes
9. conn.commit()
5. Using Prepared Statements
To prevent SQL injection and ensure security, you should always use parameterized queries,
which can be done using placeholders (%s).
1. query = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"
2. data = ("Jane Smith", 15, "9th")
3. cursor.execute(query, data)
4. conn.commit()
6. Fetching Data (Different Fetching Methods)
fetchall(): Retrieves all rows from the executed query.
1. results = cursor.fetchall()
2. for row in results:
3. print(row)
fetchone(): Retrieves the next row of a query result set.
1. result = cursor.fetchone()
2. print(result)
fetchmany(size): Retrieves the specified number of rows from the executed query.
1. results = cursor.fetchmany(2) # Fetch two rows
2. for row in results:
3. print(row)
7. Error Handling
It’s essential to handle exceptions, especially when working with databases.
1. import mysql.connector
2. from mysql.connector import Error
3.
4. try:
5. conn = mysql.connector.connect(
6. host="localhost",
7. user="your_username",
8. password="your_password",
9. database="your_database"
10. )
11. if conn.is_connected():
12. print("Connected to the database")
13. except Error as e:
14. print(f"Error: {e}")
15. finally:
16. if conn.is_connected():
17. cursor.close()
18. conn.close()
8. Closing the Connection
After completing all database operations, it’s important to close the cursor and connection to
free resources.
1. # Closing cursor and connection
2. cursor.close()
3. conn.close()
9. Full Example:
Here’s a full example showing the complete workflow from connecting to fetching data.
1. import mysql.connector
2. from mysql.connector import Error
3.
4. try:
5. # Connect to the database
6. conn = mysql.connector.connect(
7. host="localhost",
8. user="your_username",
9. password="your_password",
10. database="your_database"
11. )
12.
13. if conn.is_connected():
14. print("Connected to the database")
15.
16. # Create a cursor object
17. cursor = conn.cursor()
18.
19. # Create a table
20. cursor.execute("""
21. CREATE TABLE IF NOT EXISTS students (
22. id INT AUTO_INCREMENT PRIMARY KEY,
23. name VARCHAR(100),
24. age INT,
25. grade VARCHAR(10)
26. )
27. """)
28.
29. # Insert some data
30. cursor.execute("INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)", ("Alice", 14, "8th"))
31. cursor.execute("INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)", ("Bob", 15, "9th"))
32.
33. # Commit the changes
34. conn.commit()
35.
36. # Fetch and print the data
37. cursor.execute("SELECT * FROM students")
38. rows = cursor.fetchall()
39.
40. for row in rows:
41. print(row)
42.
43. except Error as e:
44. print(f"Error: {e}")
45. finally:
46. if conn.is_connected():
47. cursor.close()
48. conn.close()
10. Conclusion
Using Python’s mysql-connector API, you can easily interact with a MySQL database to
create tables, insert data, query records, and manage database contents securely. Always
ensure to handle exceptions and use parameterized queries to avoid security risks.
Additional Notes
rowcount Attribute
The cursor.rowcount attribute is used to find out how many rows were affected by the last
executed query. This can be useful when inserting, updating, or deleting records, or even
when fetching rows.
Example (Inserting Data)
cursor.execute(insert_data_query, data)
print("Rows affected:", cursor.rowcount)
conn.commit()
Example (Fetching Data)
cursor.execute("SELECT * FROM students")
result = cursor.fetchall()
print("Number of rows retrieved:", cursor.rowcount)
The rowcount attribute will return:
The number of rows affected for INSERT, UPDATE, and DELETE statements.
The number of rows fetched for SELECT statements.
6. Query Formatting Methods
There are several ways to format SQL queries when working with mysql-connector in
Python. The preferred method is to use parameterized queries to avoid SQL injection risks.
1. Using %s Placeholders (Parameterized Queries)
This is the safest and recommended way to pass values to SQL queries in Python.
Using %s placeholders ensures that the values are properly escaped and prevent SQL
injection attacks.
o Example:
query = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"
data = ("Alice", 15, "9th")
cursor.execute(query, data)
conn.commit()
2. String Interpolation (f-strings or .format())
While Python string formatting methods like f-strings or .format() can be used to
create SQL queries, they should be avoided for queries that include user input, as
they can make the code vulnerable to SQL injection.
o Example (f-string):
name = "Bob"
query = f"SELECT * FROM students WHERE name = '{name}'"
cursor.execute(query)
o Example (.format):
query = "SELECT * FROM students WHERE name = '{}'".format(name)
cursor.execute(query)
Caution: Direct string formatting should not be used for user input due to the risk of
SQL injection. Use parameterized queries (%s) instead.
3. Using Named Placeholders
With mysql-connector, you can also use named placeholders in the query for better
readability. The dictionary is passed to the execute() method.
o Example:
query = "INSERT INTO students (name, age, grade) VALUES (%(name)s,
%(age)s, %(grade)s)"
data = {"name": "Charlie", "age": 14, "grade": "8th"}
cursor.execute(query, data)
conn.commit()