ubuntu中mysql怎么退出命令_如何使用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 10Server 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 16Server 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 changedmysql>上面的示例程序首先使用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 syscon_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 6Server 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 namesYou can turn off this feature to get a quicker startup with -ADatabase changedmysql> 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的記錄。我們還可以使用其他任何字段名稱刪除對應記錄。
本文摘自《寫給系統管理員的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的通信;
■ 自動化數據庫管理并執行統計分析。
總結
以上是生活随笔為你收集整理的ubuntu中mysql怎么退出命令_如何使用Python进行MySQL数据库管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转化百分比_小秘诀教你如何快速提升大众点
- 下一篇: centos7 没有pip命令_Linu