Connecting MySQL to Python
Connecting MySQL to Python and performing various operations involves a few key steps.
1. Install the MySQL Connector
First, you need the mysql-connector-python library, which allows Python to communicate with MySQL.
You can install it using pip from your terminal or command prompt:
pip install mysql-connector-python
2. Connect to the Database
Once the connector is installed, you can import the library and establish a connection to your MySQL
database. You'll need to provide your database credentials: host, user, password, and database.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database_name"
)
3. Create a Cursor
A cursor is an object that you use to execute SQL queries and fetch results. You create a cursor from
the connection object you established in the previous step.
# Create a cursor object
mycursor = mydb.cursor()
The cursor object is used to execute SQL queries.
4. Execute SQL Queries
With the cursor created, you can now execute SQL queries using the execute() method. Here's an
example of how to select data from a table named customers:
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The fetchall() method fetches all the rows from the last executed query result set. You can then iterate
through the results to process the data as needed.
The fetchone() method fetches one row from the last executed query result set.
The fetchmany(n) method fetches n rows from the last executed query result set.
5. Insert Records
To insert new records, you use the INSERT INTO SQL command within the cursor's execute() method.
It's best practice to use placeholders (%s) to prevent SQL injection vulnerabilities. After executing the
query, you must call mydb.commit() to save the changes to the database.
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John Doe", "123 Main St")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
6. Update Records
To update existing records, you use the UPDATE SQL command. The WHERE clause is crucial here to
specify which records to change. As with insertions, you use placeholders and commit the changes.
sql = "UPDATE customers SET address = %s WHERE name = %s"
val = ("456 Oak Ave", "John Doe")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) updated.")
7. Delete Records
To delete records, you use the DELETE FROM SQL command. The WHERE clause is essential to specify
which records should be removed.
sql = "DELETE FROM customers WHERE address = %s"
val = ("456 Oak Ave",)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted.")
8. Close the Connection
After completing your operations, it's good practice to close the cursor and the database connection to
free up resources.
mycursor.close()
mydb.close()