Databases are essential for storing and managing structured data. In this tutorial, you'll learn how to interact with a MySQL database using the mysql-connector-python library in Python. We'll cover creating databases and tables, inserting data, selecting data with conditions, updating records, deleting records, ordering results, limiting results, and joining tables.
MySQL is one of the most popular relational database management systems (RDBMS). The mysql-connector-python library allows you to connect your Python applications to MySQL databases. In this tutorial, we'll go through the basic operations you need to perform on a MySQL database using Python.
Before performing any operations, you need to establish a connection to the MySQL server. Here's how you can do it:
connect() method from the mysql.connector module.1import mysql.connector23# Establishing the connection4mydb = mysql.connector.connect(5host="localhost",6user="yourusername",7password="yourpassword"8)910print(mydb)
<mysql.connector.connection.MySQLConnection object at 0x7f8b1c1b1d30>
Once connected, you can create a new database using the CREATE DATABASE SQL statement.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword"7)89mycursor = mydb.cursor()1011# Creating a database12mycursor.execute("CREATE DATABASE IF NOT EXISTS testdb")
After creating a database, you can create tables within it. Here's how to create a table named customers:
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Creating a table13mycursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
You can insert data into the customers table using the INSERT INTO SQL statement.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Inserting a record13sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"14val = ("John Doe", "123 Main St")15mycursor.execute(sql, val)1617# Committing the transaction18mydb.commit()1920print(mycursor.rowcount, "record inserted.")
1 record inserted.
To retrieve data from the database, use the SELECT SQL statement.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Selecting all records13mycursor.execute("SELECT * FROM customers")1415# Fetching the results16myresult = mycursor.fetchall()1718for x in myresult:19print(x)
(1, 'John Doe', '123 Main St')
You can filter the data using the WHERE clause.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Selecting records with a condition13sql = "SELECT * FROM customers WHERE address = %s"14adr = ("123 Main St",)15mycursor.execute(sql, adr)1617myresult = mycursor.fetchall()1819for x in myresult:20print(x)
(1, 'John Doe', '123 Main St')
To update data in the database, use the UPDATE SQL statement.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Updating a record13sql = "UPDATE customers SET address = %s WHERE name = %s"14val = ("456 Elm St", "John Doe")15mycursor.execute(sql, val)1617# Committing the transaction18mydb.commit()1920print(mycursor.rowcount, "record(s) affected")
1 record(s) affected
To delete data from the database, use the DELETE SQL statement.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Deleting a record13sql = "DELETE FROM customers WHERE name = %s"14adr = ("John Doe",)15mycursor.execute(sql, adr)1617# Committing the transaction18mydb.commit()1920print(mycursor.rowcount, "record(s) deleted")
1 record(s) deleted
You can order the results using the ORDER BY clause.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Selecting and ordering records13sql = "SELECT * FROM customers ORDER BY name"14mycursor.execute(sql)1516myresult = mycursor.fetchall()1718for x in myresult:19print(x)
To limit the number of results returned, use the LIMIT clause.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Selecting and limiting records13sql = "SELECT * FROM customers LIMIT 5"14mycursor.execute(sql)1516myresult = mycursor.fetchall()1718for x in myresult:19print(x)
You can join tables using the JOIN clause.
1import mysql.connector23mydb = mysql.connector.connect(4host="localhost",5user="yourusername",6password="yourpassword",7database="testdb"8)910mycursor = mydb.cursor()1112# Joining tables13sql = "SELECT customers.name, orders.order_id FROM customers INNER JOIN orders ON customers.id = orders.customer_id"14mycursor.execute(sql)1516myresult = mycursor.fetchall()1718for x in myresult:19print(x)
Let's create a complete mini-program that performs all the operations we've learned so far.
1import mysql.connector23def create_db_and_table():4mydb = mysql.connector.connect(5host="localhost",6user="yourusername",7password="yourpassword"8)9mycursor = mydb.cursor()10mycursor.execute("CREATE DATABASE IF NOT EXISTS testdb")11mydb.database = "testdb"12mycursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")1314def insert_data():15mydb = mysql.connector.connect(16host="localhost",17user="yourusername",18password="yourpassword",19database="testdb"20)21mycursor = mydb.cursor()22sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"23val = ("John Doe", "123 Main St")24mycursor.execute(sql, val)25mydb.commit()26print(mycursor.rowcount, "record inserted.")2728def select_data():29mydb = mysql.connector.connect(30host="localhost",31user="yourusername",32password="yourpassword",33database="testdb"34)35mycursor = mydb.cursor()36mycursor.execute("SELECT * FROM customers")37myresult = mycursor.fetchall()38for x in myresult:39print(x)4041def update_data():42mydb = mysql.connector.connect(43host="localhost",44user="yourusername",45password="yourpassword",46database="testdb"47)48mycursor = mydb.cursor()49sql = "UPDATE customers SET address = %s WHERE name = %s"50val = ("456 Elm St", "John Doe")51mycursor.execute(sql, val)52mydb.commit()53print(mycursor.rowcount, "record(s) affected")5455def delete_data():56mydb = mysql.connector.connect(57host="localhost",58user="yourusername",59password="yourpassword",60database="testdb"61)62mycursor = mydb.cursor()63sql = "DELETE FROM customers WHERE name = %s"64adr = ("John Doe",)65mycursor.execute(sql, adr)66mydb.commit()67print(mycursor.rowcount, "record(s) deleted")6869if __name__ == "__main__":70create_db_and_table()71insert_data()72select_data()73update_data()74delete_data()
mysql.connector.connect() with host, user, and password.CREATE DATABASE.CREATE TABLE.INSERT INTO.SELECT.UPDATE.DELETE.ORDER BY.LIMIT.JOIN.Now that you've learned how to interact with MySQL databases using Python, the next step is to explore MongoDB. In the upcoming tutorial, "Python MongoDB (Insert, Find, Update, Delete)", we'll cover similar operations but for MongoDB. This will give you a comprehensive understanding of working with two popular NoSQL and SQL databases in Python.
Stay tuned!