本节我们将学习使用Python进行MySQL数据库管理。Python有多种用于MySQL数据库管理的模块,这里使用MySQLdb模块。MySQLdb模块是MySQL数据库服务器的接口,用于向Python提供数据库API。
首先我们需要安装MySQL和Python的MySQLdb包,在终端中运行以下命令。
$ sudo apt install mysql-server此命令安装MySQL服务器和各种相关软件包。安装软件包时,系统会提示我们输入MySQL root账户的密码。
以下命令用于查看要安装的MySQLdb包。
$ apt-cache search MySQLdb以下命令安装MySQL的Python接口。
$ sudo apt-get install python3-mysqldb现在检查MySQL是否正确安装,在终端中运行以下命令。
student@ubuntu:~$ sudo mysql -u root –p运行命令后,如下所示。
Enter password:Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
运行sudo mysql -u root -p,打开MySQL控制台。使用以下部分命令列出数据库和表,并使用数据库来存储我们的操作。
列出所有数据库。
show databases;使用数据库。
use database_name;列出所有表。
show tables;以上就是列出所有数据库、使用数据库和列出表的命令。
每当退出MySQL控制台并在一段时间后再次登录时,我们就必须使用use database_name命令,将所有操作保存在数据库中。我们可以通过以下示例详细了解这一点。
现在,我们在MySQL控制台中使用create database语句创建一个数据库。运行mysql -u root -p打开MySQL控制台,然后输入在安装时设置的密码,按Enter键。最后创建数据库。本节将创建一个名为test的数据库,后面也将使用此数据库。
在终端中运行以下命令。
student@ubuntu:~/work/mysql_testing$ sudo mysql -u root –p运行命令后,如下所示。
Enter password:Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 16
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.10 sec)
mysql> create database test;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| test |
+--------------------+
5 rows in set (0.00 sec)
mysql> use test;
Database changed
mysql>
上面的示例程序首先使用show databases列出了所有数据库,接着使用create database创建了数据库测试,然后再次使用show databases以查看数据库是否已创建。我们可以看到数据库现已创建,接着使用该数据库来存储正在进行的操作结果。
现在将创建一个用户并为该用户授予权限,运行以下命令。
mysql> create user 'test_user'@'localhost' identified by 'test123';Query OK, 0 rows affected (0.06 sec)
mysql> grant all on test.* to 'test_user'@'localhost';
Query OK, 0 rows affected (0.02 sec)
mysql>
这里创建了一个test_user用户,该用户的密码是test123。然后为test_user用户授予所有权限。最后通过quit命令或者exit命令退出MySQL控制台。
接下来我们将学习获取数据库版本号、创建表、向表插入一些数据、检索数据、更新数据和删除数据的示例程序。
1 获取数据库版本号
我们来看获取数据库版本号的示例程序。创建一个脚本,命名为get_database_version.py,并在其中写入以下代码。
import MySQLdb as mdbimport sys
con_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
cur_obj = con_obj.cursor()
cur_obj.execute("SELECT VERSION()")
version = cur_obj.fetchone()
print ("Database version: %s " % version)
con_obj.close()
在运行此脚本之前,请务必保证已经完成上述步骤,不应该跳过这些步骤。
运行脚本程序,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 get_database_version.py输出如下。
Database version: 5.7.24-0ubuntu0.18.04.1上面的示例程序获取了数据库版本号。首先导入了MySQLdb模块,然后根据给出的包含用户名、密码、数据库名的字符串连接了数据库,接着创建了一个用于执行SQL查询的cursor对象。在execute()函数中,给出了一个SQL查询语句。fetchone()函数获取了一行查询结果。最后输出结果。close()方法用于关闭数据库连接。
2 创建表并插入数据
现在我们创建一个表,并向其中插入一些数据。创建一个脚本,命名为create_insert_data.py,并在其中写入以下代码。
import MySQLdb as mdbcon_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("DROP TABLE IF EXISTS books")
cur_obj.execute("CREATE TABLE books(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(100))")
cur_obj.execute("INSERT INTO books(Name) VALUES('Harry Potter')")
cur_obj.execute("INSERT INTO books(Name) VALUES('Lord of the rings')")
cur_obj.execute("INSERT INTO books(Name) VALUES('Murder on the Orient Express')")
cur_obj.execute("INSERT INTO books(Name) VALUES('The adventures of Sherlock Holmes')")
cur_obj.execute("INSERT INTO books(Name) VALUES('Death on the Nile')")
print("Table Created !!")
print("Data inserted Successfully !!")
运行脚本程序,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 create_insert_data.py输出如下。
Table Created !!Data inserted Successfully !!
要检查表是否已成功被创建,需打开MySQL控制台并运行以下命令。
student@ubuntu:~/work/mysql_testing$ sudo mysql -u root -p运行命令后,输出如下。
Enter password:Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql>
mysql> use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| books |
+----------------+
1 row in set (0.00 sec)
我们可以看到表books已经被创建。
3 检索数据
现在我们使用select语句从表中检索数据,这里从books表中检索数据。创建一个脚本,命名为retrieve_data.py,并在其中写入以下代码。
import MySQLdb as mdbcon_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("SELECT * FROM books")
records = cur_obj.fetchall()
for r in records:
print(r)
运行脚本程序,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 retrieve_data.py输出如下。
(1, 'Harry Potter')(2, 'Lord of the rings')
(3, 'Murder on the Orient Express')
(4, 'The adventures of Sherlock Holmes')
(5, 'Death on the Nile')
上面的示例程序从表中检索了数据。首先使用了MySQLdb模块,接着连接了数据库,并创建了一个cursor对象来执行SQL查询。在execute()函数中,给出了一个select语句。最后输出了查询到的记录。
4 更新数据
如果想在数据库记录中进行一些更改,我们可以使用update语句,以下是一个update语句的示例程序。我们创建一个脚本,命名为update_data.py,并在其中写入以下代码。
import MySQLdb as mdbcon_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
cur_obj = con_obj.cursor()
cur_obj.execute("UPDATE books SET Name = 'Fantastic Beasts' WHERE Id = 1")
try:
con_obj.commit()
except:
con_obj.rollback
运行脚本程序,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 update_data.py现在检查数据库中的记录是否已更新,运行retrieve_data.py,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 retrieve_data.py输出如下。
(1, 'Fantastic Bcasts')(2, 'Lord of the rings')
(3, 'Murder on the Orient Express')
(4, 'The adventures of Sherlock Holmes')
(5, 'Death on the Nile')
我们可以看到ID为1的数据已更新。上面的示例程序在execute()中给出了一个update语句,用于更新ID为1的记录。
5 删除数据
现在我们使用delete语句从表中删除特定记录,以下是删除数据的示例程序。创建一个脚本,命名为delete_data.py,并在其中写入以下代码。
import MySQLdb as mdbcon_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
cur_obj = con_obj.cursor()
cur_obj.execute("DELETE FROM books WHERE Id = 5");
try:
con_obj.commit()
except:
con_obj.rollback()
运行脚本程序,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 delete_data.py现在检查数据库中的记录是否已删除,运行retrieve_data.py,如下所示。
student@ubuntu:~/work/mysql_testing$ python3 retrieve_data.py输出如下。
(1, 'Fantastic Beasts')(2, 'Lord of the rings')
(3, 'Murder on the Orient Express')
(4, 'The adventures of Sherlock Holmes')
我们可以看到ID为5的记录已被删除。上面的示例程序使用delete语句删除特定记录,这里删除了ID为5的记录。我们还可以使用其他任何字段名称删除对应记录。