Python MySQL - mysql-connector Driver
MySQL is the most popular relational database management system. If you are not familiar with MySQL, you can read our MySQL Tutorial.
In this chapter we introduce the use of mysql-connector to connect to and use MySQL, mysql-connector Is MySQL the officially provided driver.
We can use the pip command to install mysql-connector:
python -m pip install mysql-connector
Use the following code to test whether mysql-connector is installed successfully:
demo_mysql_test.py:
import
mysql
.
connector
Run the above code; if no error occurs, the installation is successful.
NoteNote:If your MySQL is version 8.0, the password plugin verification method has changed; earlier versions used mysql_native_password, while 8.0 uses caching_sha2_password, so some changes are needed:
First modify the my.ini configuration:
[mysqld]
default_authentication_plugin=mysql_native_password
Then execute the following command under mysql to change the password:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新密码';
For more information, refer to:Python MySQL 8.0 Connection Issues。
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
)
(
mydb
)
Create the database
Creating a database uses the "CREATE DATABASE" statement; the following creates a database named runoob_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 runoob_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
:
(
x
)
Or we can connect directly to the database; if it 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
=
"
runoob_db
"
)
Create a data table
Creating a data table uses the "CREATE TABLE" statement. Before creating a table, ensure the database exists; the following creates a table named sites :
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_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 fields name and url.

We can also use the "SHOW TABLES" statement to check whether the data table exists:
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SHOW TABLES
"
)
for
x
in
mycursor
:
(
x
)
Primary key settings
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 starting value is 1 and increments.
If our table is already created, we need to use ALTER TABLE to 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
=
"
runoob_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
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))
"
)
Insert data
Inserting data uses the "INSERT INTO" Statement:
demo_mysql_test.py:
statement to insert a record into the sites table.
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
INSERT INTO sites (name, url) VALUES (%s, %s)
"
val
=
(
"
RUNOOB
"
,
"
https://www.runoob.com
"
)
mycursor
.
execute
(
sql
,
val
)
mydb
.
commit
(
)
The data table content has been updated; this statement must be used
(
mycursor
.
rowcount
,
"
Record inserted successfully.
"
)
After executing the code, the output is:
1 记录插入成功
Batch insert
Batch insert uses the executemany() method, whose second parameter 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
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
INSERT INTO sites (name, url) VALUES (%s, %s)
"
val
=
[
(
'
'
,
'
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
(
mycursor
.
rowcount
,
"
Record inserted successfully.
"
)
After executing the code, the output is:
4 记录插入成功。
After executing the above code, we can check the records in the data table:

If we want to get the ID of the record after insertion, we can use the following code:
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_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
(
)
(
"
1 record inserted, ID:
"
,
mycursor
.
lastrowid
)
After executing the code, the output is:
1 条记录已插入, ID: 6
Query data
Querying data uses the SELECT Statement:
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SELECT * FROM sites
"
)
myresult
=
mycursor
.
fetchall
(
)
fetchall() to get all records
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(1, 'RUNOOB', 'https://www.runoob.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 specified field data:
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SELECT name, url FROM sites
"
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
('RUNOOB', 'https://www.runoob.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 fetchone() method in the component:
demo_mysql_test.py:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SELECT * FROM sites
"
)
myresult
=
mycursor
.
fetchone
(
)
(
myresult
)
After executing the code, the output is:
(1, 'RUNOOB', 'https://www.runoob.com')
where condition statement
If we want to read data matching specified conditions, we can use where Statement:
demo_mysql_test.py
to read records where the name field is RUNOOB:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
SELECT * FROM sites WHERE name ='RUNOOB'
"
mycursor
.
execute
(
sql
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(1, 'RUNOOB', 'https://www.runoob.com')
You can also use the wildcard %:
demo_mysql_test.py
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
SELECT * FROM sites WHERE url LIKE '%oo%'
"
mycursor
.
execute
(
sql
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
To prevent SQL injection attacks in database queries, we can use the %s placeholder to escape the query conditions:
demo_mysql_test.py
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
SELECT * FROM sites WHERE name = %s
"
na
=
(
"
RUNOOB
"
,
)
mycursor
.
execute
(
sql
,
na
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
Sorting
Query result sorting can use the ORDER BY statement; the default sort order is ascending, with the keyword ASC; to set descending order, set the keyword DESC。
demo_mysql_test.py
Sort by the name field in ascending alphabetical order:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
SELECT * FROM sites ORDER BY name
"
mycursor
.
execute
(
sql
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(3, 'Github', 'https://www.github.com')
(2, 'Google', 'https://www.google.com')
(1, 'RUNOOB', 'https://www.runoob.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(4, 'Taobao', 'https://www.taobao.com')
(6, 'Zhihu', 'https://www.zhihu.com')
Descending sort example:
demo_mysql_test.py
Sort by the name field in descending alphabetical order:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
SELECT * FROM sites ORDER BY name DESC
"
mycursor
.
execute
(
sql
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(6, 'Zhihu', 'https://www.zhihu.com')
(4, 'Taobao', 'https://www.taobao.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
Limit
If we want to set the amount of query data, 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
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SELECT * FROM sites LIMIT 3
"
)
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(1, 'RUNOOB', 'https://www.runoob.com')
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
You can also specify a starting position; the keyword is OFFSET:
demo_mysql_test.py
Read the first 3 records starting from the second:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
mycursor
.
execute
(
"
SELECT * FROM sites LIMIT 3 OFFSET 1
"
)
0 is the first record, 1 is the second, and so on
myresult
=
mycursor
.
fetchall
(
)
for
x
in
myresult
:
(
x
)
After executing the code, the output is:
(2, 'Google', 'https://www.google.com')
(3, 'Github', 'https://www.github.com')
(4, 'Taobao', 'https://www.taobao.com')
Delete records
Deleting records uses the "DELETE FROM" Statement:
demo_mysql_test.py
statement to delete records where name is stackoverflow:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
DELETE FROM sites WHERE name = 'stackoverflow'
"
mycursor
.
execute
(
sql
)
mydb
.
commit
(
)
(
mycursor
.
rowcount
,
"
record(s) deleted
"
)
After executing the code, the output is:
1 条记录删除
**Note:** Use delete statements with caution. Make sure to specify a WHERE condition; otherwise the entire table's data will be deleted.
To prevent SQL injection attacks in database queries, we can use the %s placeholder to escape the delete statement conditions:
demo_mysql_test.py
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
DELETE FROM sites WHERE name = %s
"
na
=
(
"
stackoverflow
"
,
)
mycursor
.
execute
(
sql
,
na
)
mydb
.
commit
(
)
(
mycursor
.
rowcount
,
"
record(s) deleted
"
)
After executing the code, the output is:
1 条记录删除
Update table data
Updating the data table uses the "UPDATE" Statement:
demo_mysql_test.py
statement to change the field data where name is Zhihu to ZH:
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'
"
mycursor
.
execute
(
sql
)
mydb
.
commit
(
)
(
mycursor
.
rowcount
,
"
record(s) modified
"
)
After executing the code, the output is:
1 条记录被修改
**Note:** The UPDATE statement must specify a WHERE condition; otherwise the entire table's data will be updated.
To prevent SQL injection attacks in database queries, we can use the %s placeholder to escape the update statement conditions:
demo_mysql_test.py
import
mysql
.
connector
mydb
=
mysql
.
connector
.
connect
(
host
=
"
localhost
"
,
user
=
"
root
"
,
passwd
=
"
123456
"
,
database
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
UPDATE sites SET name = %s WHERE name = %s
"
val
=
(
"
Zhihu
"
,
"
ZH
"
)
mycursor
.
execute
(
sql
,
val
)
mydb
.
commit
(
)
(
mycursor
.
rowcount
,
"
record(s) modified
"
)
After executing the code, the output is:
1 条记录被修改
Delete table
Deleting a table uses the "DROP TABLE" statement; the IF EXISTS keyword is used to check 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
=
"
runoob_db
"
)
mycursor
=
mydb
.
cursor
(
)
sql
=
"
DROP TABLE IF EXISTS sites
"
Delete the data table sites
mycursor
.
execute
(
sql
)