[MySQL & Python] 2. 資料庫互動操作(MySQL客戶端與Python)
阿新 • • 發佈:2022-04-01
MySQL內建客戶端操作
- 檢視系統資料庫。
show databases
- 建立資料庫
CREATE TABLE 資料庫 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
使用utf8編碼,避免中文漢字問題。COLLATE 影響排序規則。
- 刪除資料庫
DROP DATABASE 資料庫名
CREATE DATABASE day25db DEFAULT CHARSET utf8 COLLATE utf8_general_ci; Query OK, 1 row affected (0.01 sec) mysql> SHOW DATABASES;+--------------------+ | Database | +--------------------+ | information_schema | | day25db | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.00 sec)
DROP DATABASE day25db;
Query OK, 0 rows affected (0.02 sec)
- 進入資料庫
use 資料庫名
- 檢視資料庫中的表
show tables
mysql> use information_schema Database changed mysql> show tables; +---------------------------------------+ | Tables_in_information_schema | +---------------------------------------+ | CHARACTER_SETS | | COLLATIONS || COLLATION_CHARACTER_SET_APPLICABILITY | | INNODB_SYS_FOREIGN | | INNODB_SYS_TABLESTATS | +---------------------------------------+
Python操作
#安裝pymysql模組
LeodeMBP:~ leo$ pip3 install pymysql Collecting pymysql Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 43.8/43.8 KB 67.5 kB/s eta 0:00:00 Installing collected packages: pymysql Successfully installed pymysql-1.0.2
#匯入pymysql
import pymysql
#建立資料庫連結物件至mysql資料庫
conn = pymysql.connect(host = '127.0.0.1' , port = 3306, user = 'root' , passwd = 'root123' , charset = 'utf8')
#建立遊標物件,基於遊標可以傳送指令。
cursor = conn.cursor()
#檢視系統的資料庫
cursor.execute('show databases')
result = cursor.fetchall()
print(result)
(('information_schema',), ('day25db',), ('mysql',), ('performance_schema',), ('sys',))
#建立資料庫
cursor.execute("CREATE DATABASE day25db DEFAULT CHARSET utf8 COLLATE utf8_general_ci")
conn.commit() #提交事務來儲存更改
#刪除資料庫
cursor.execute("DROP DATABASE day25db")
conn.commit()
#進入資料庫,檢視所有表
cursor.execute("use mysql")
cursor.execute("show tables")
result = cursor.fetchall()
print(result)
#關閉連結
cursor.close()
conn.close()