如何使用Python进行MySQL数据库管理

本节我们将学习使用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 mdb
import 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 mdb

con_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 mdb

con_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 mdb
con_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 mdb

con_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的记录。我们还可以使用其他任何字段名称删除对应记录。

本文摘自《写给系统管理员的Python脚本编程指南》,[印度] 甘尼什·桑吉夫·奈克(Ganesh,Sanjiv,Naik) 著,张成悟 译。

  • 从基础到高级编程,全面系统地介绍Python脚本在系统管理中的作用。
  • 市场上少见的介绍将Python脚本应用于系统管理的图书。
  • 本书附有配套资源,帮助读者学以致用,将所学应用到真实场景中。

本书首先介绍Python的安装,并讲解编程基础知识。然后,本书将侧重于解析整个开发过程,从配置到准备再到构建 不同的工具,包括IT管理员的日常活动(文本处理、正则表达式、文件存档和加密)、网络管理(套接字编程、电子邮 件处理、使用Telnet/SSH远程控制设备以及SNMP/DHCP等协议)、创建图形用户界面、网站处理(Apache日志 文件处理、SOAP和REST API通信、Web抓取),以及数据库管理(MySQL和相似数据库数据管理、数据分析和报告)。学完本书,读者将能够使用Python功能构建强大的工具以解决具有挑战性的实际任务。

读者将学到以下内容:
■ 了解如何安装Python和调试Python脚本;
■ 了解和编写用于自动化测试和日常管理活动的脚本;
■ 了解如何编写用于文本处理、加密、解密和归档的脚本;
■ 处理PDF、Excel、CSV和文本文件,并生成报告;
■ 编写用于远程网络管理(包括处理电子邮件)的脚本;
■ 使用图形用户界面构建交互式工具;
■ 处理Apache日志文件,以及SOAP和REST API的通信;
■ 自动化数据库管理并执行统计分析。

发布了496 篇原创文章 · 获赞 280 · 访问量 87万+

猜你喜欢

转载自blog.csdn.net/epubit17/article/details/104032554