Python Interface With SQL Databases
Python Interface With SQL Databases
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:
Once the mysql-connector library is installed, you can connect to a MySQL database. For
this, you need:
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.
You can use the cursor.execute() method to run SQL queries. Let’s look at a few
examples:
Creating a Table
Inserting Data
Fetching Data
Deleting Data
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()
1. results = cursor.fetchall()
2. for row in results:
3. print(row)
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
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()
After completing all database operations, it’s important to close the cursor and connection to
free resources.
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.
cursor.execute(insert_data_query, data)
print("Rows affected:", cursor.rowcount)
conn.commit()
The number of rows affected for INSERT, UPDATE, and DELETE statements.
The number of rows fetched for SELECT statements.
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.
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):
Caution: Direct string formatting should not be used for user input due to the risk of
SQL injection. Use parameterized queries (%s) instead.