Python MySQL - mysql-connector Driver

MySQL is the most popular relational database management system. If you are not familiar with MySQL, you can read ourMySQL tutorial.

This chapter introduces usingmysql-connectorto connect to and use MySQL,mysql-connectorYesMySQLthe officially provided driver.

We can use thepipcommand to installmysql-connector:

python -m pip install mysql-connector

Use the following code to test whether mysql-connector was installed successfully:

demo_mysql_test.py:

import mysql.connector

Execute the above code. If no errors occur, the installation was successful.

NoteNote:If your MySQL is version 8.0, the password plugin authentication method has changed. The early version used mysql_native_password, and version 8.0 uses caching_sha2_password, so some changes need to be made:

First modify the my.ini configuration:

[mysqld]
default_authentication_plugin=mysql_native_password

Then execute the following commands under MySQL to change the password:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新密码';

For more content, you can refer to:Python MySQL 8.0 Connection Problem。


Creating a Database Connection

You can use the following code to connect to the database:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", # Database host address user="yourusername", # Database username passwd="yourpassword" # Database password ) print(mydb)

Creating a Database

To create a database, use the "CREATE DATABASE" statement. The following creates a database named example_db:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE example_db")

Before creating a database, we can also use the "SHOW DATABASES" statement to check whether the database exists:

demo_mysql_test.py:

Output the list of all databases:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456" ) mycursor = mydb.cursor() mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)

Alternatively, we can connect directly to the database. If the database does not exist, an error message will be output:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" )

Creating a Data Table

To create a data table, use the"CREATE TABLE"statement. Before creating a data table, you need to ensure that the database already exists. The following creates asitesdata table:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
After successful execution, we can see the data table sites created in the database, with the fields name and url.

We can also use the"SHOW TABLES"statement to check whether the data table already exists:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x)

Primary Key Setup

When creating a table, we generally set a primary key (PRIMARY KEY). We can use the"INT AUTO_INCREMENT PRIMARY KEY"statement to create a primary key. The primary key starts at 1 and increments step by step.

If our table has already been created, we need to useALTER TABLEto add a primary key to the table:

demo_mysql_test.py:

Add a primary key to the sites table.

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

If you have not yet created the sites table, you can directly use the following code to create it.

demo_mysql_test.py:

Create a primary key for the table.

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")

Insert Data

To insert data, use the"INSERT INTO"statement:

demo_mysql_test.py:

Insert a record into the sites table.

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "INSERT INTO sites (name, url) VALUES (%s, %s)" val = ("EXAMPLE", "https://www.example.com") mycursor.execute(sql, val) mydb.commit() # The data table content has been updated; this statement must be used print(mycursor.rowcount, "The record was inserted successfully.")

Execute the code, and the output result is:

1 记录插入成功

Batch Insert

For batch insertion, use theexecutemany()method. The second parameter of this method is a list of tuples, containing the data we want to insert:

demo_mysql_test.py:

Insert multiple records into the sites table.

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "INSERT INTO sites (name, url) VALUES (%s, %s)" val = [ ('Google', 'https://www.google.com'), ('Github', 'https://www.github.com'), ('Taobao', 'https://www.taobao.com'), ('stackoverflow', 'https://www.stackoverflow.com/') ] mycursor.executemany(sql, val) mydb.commit() # The data table content has been updated; this statement must be used print(mycursor.rowcount, "The records were inserted successfully.")

Execute the code, and the output result is:

4 记录插入成功。

After executing the above code, we can look at the records in the data table:

If we want to get the ID of the record after inserting the data, we can use the following code:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "INSERT INTO sites (name, url) VALUES (%s, %s)" val = ("Zhihu", "https://www.zhihu.com") mycursor.execute(sql, val) mydb.commit() print("1 record inserted, ID:", mycursor.lastrowid)

Execute the code, and the output result is:

1 条记录已插入, ID: 6

Query Data

To query data, use theSELECTstatement:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM sites") myresult = mycursor.fetchall() # fetchall() gets all records for x in myresult: print(x)

Execute the code, and the output result is:

(1, 'EXAMPLE', 'https://www.example.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(6, 'Zhihu', 'https://www.zhihu.com')

You can also read data from specified fields:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SELECT name, url FROM sites") myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

('EXAMPLE', 'https://www.example.com')
('Google', 'https://www.google.com')
('Github', 'https://www.github.com')
('Taobao', 'https://www.taobao.com')
('stackoverflow', 'https://www.stackoverflow.com/')
('Zhihu', 'https://www.zhihu.com')

If we only want to read one record, we can use thefetchone()method:

demo_mysql_test.py:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM sites") myresult = mycursor.fetchone() print(myresult)

Execute the code, and the output result is:

(1, 'EXAMPLE', 'https://www.example.com')

WHERE Condition Statement

If we want to read data with specified conditions, we can use thewherestatement:

demo_mysql_test.py

Read records where the name field is EXAMPLE:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "SELECT * FROM sites WHERE name ='EXAMPLE'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(1, 'EXAMPLE', 'https://www.example.com')

You can also use wildcards%:

demo_mysql_test.py

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "SELECT * FROM sites WHERE url LIKE '%oo%'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(1, 'EXAMPLE', 'https://www.example.com')
(2, 'Google', 'https://www.google.com')

To prevent SQL injection attacks in database queries, we can use%splaceholder to escape the query conditions:

demo_mysql_test.py

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "SELECT * FROM sites WHERE name = %s" na = ("EXAMPLE", ) mycursor.execute(sql, na) myresult = mycursor.fetchall() for x in myresult: print(x)

Sorting

Query results can be sorted using theORDER BYstatement. The default sorting method is ascending order, with the keywordASC. If you want to set descending order, you can set the keywordDESC。

demo_mysql_test.py

Sort in ascending order by the letters of the name field:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "SELECT * FROM sites ORDER BY name" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(3, 'Github', 'https://www.github.com')
(2, 'Google', 'https://www.google.com')
(1, 'EXAMPLE', 'https://www.example.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(4, 'Taobao', 'https://www.taobao.com')
(6, 'Zhihu', 'https://www.zhihu.com')

Example of descending order sorting:

demo_mysql_test.py

Sort in descending order by the letters of the name field:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "SELECT * FROM sites ORDER BY name DESC" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(6, 'Zhihu', 'https://www.zhihu.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(1, 'EXAMPLE', 'https://www.example.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')

Limit

If we want to set the amount of data to query, we can use the"LIMIT"statement to specify

demo_mysql_test.py

Read the first 3 records:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM sites LIMIT 3") myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(1, 'EXAMPLE', 'https://www.example.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')

You can also specify the starting position. The keyword used isOFFSET:

demo_mysql_test.py

Read the first 3 records starting from the second record:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1") # 0 is the first, 1 is the second, and so on myresult = mycursor.fetchall() for x in myresult: print(x)

Execute the code, and the output result is:

(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
(4, 'Taobao', 'https://www.taobao.com')

Delete Record

To delete records, use the"DELETE FROM"statement:

demo_mysql_test.py

Delete records where name is stackoverflow:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "DELETE FROM sites WHERE name = 'stackoverflow'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")

Execute the code, and the output result is:

1  条记录删除

Note:Use the DELETE statement with caution. Make sure the WHERE condition is specified in the DELETE statement, otherwise all data in the table will be deleted.

To prevent SQL injection attacks in database queries, we can use%splaceholder to escape the conditions of the DELETE statement:

demo_mysql_test.py

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "DELETE FROM sites WHERE name = %s" na = ("stackoverflow", ) mycursor.execute(sql, na) mydb.commit() print(mycursor.rowcount, "record(s) deleted")

Execute the code, and the output result is:

1  条记录删除

Update Table Data

To update a data table, use the"UPDATE"statement:

demo_mysql_test.py

Change the field data with name Zhihu to ZH:

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) modified")

Execute the code, and the output result is:

1  条记录被修改

Note:Make sure the UPDATE statement specifies a WHERE condition, otherwise all data in the table will be updated.

To prevent SQL injection attacks in database queries, we can use the %s placeholder to escape the conditions of the UPDATE statement:

demo_mysql_test.py

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "UPDATE sites SET name = %s WHERE name = %s" val = ("Zhihu", "ZH") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record(s) modified")

Execute the code, and the output result is:

1  条记录被修改

Delete Table

To delete a table, use the"DROP TABLE"statement.IF EXISTSThe keyword is used to determine whether the table exists, and it is only deleted if it exists:

demo_mysql_test.py

import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="example_db" ) mycursor = mydb.cursor() sql = "DROP TABLE IF EXISTS sites" # Delete the data table sites mycursor.execute(sql)
Other Extensions