如何使用Python進行MySQL資料庫管理

程序員書屋 發佈 2020-01-18T22:16:52+00:00

讀者將學到以下內容:■了解如何安裝Python和調試Python腳本;■ 了解和編寫用於自動化測試和日常管理活動的腳本;■ 了解如何編寫用於文本處理、加密、解密和歸檔的腳本;■ 處理PDF、Excel、CSV和文本文件,並生成報告;■ 編寫用於遠程網絡管理的腳本;■ 使用圖形用戶

本節我們將學習使用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的通信;

■ 自動化資料庫管理並執行統計分析。

關鍵字: