Python連接MySQL數據庫的多種方式上篇文章分享了windows下載mysql5.7壓縮包配置安裝mysql
後續可以選擇
①在本地創建一個數據庫,使用navicat工具導出遠程測試服務器的數據庫至本地,用於學習操作,且不影響測試服務器的數據
②連接測試服務器的數據庫賬號和密碼,在測試服務器上操作,內部測試服務器的數據庫賬號和密碼在分配時會給不同賬號做權限限制,如不同賬號允許登錄的方式、開放的數據庫範圍、賬號可讀寫操作的權限都會不一樣,若出現一直使用代碼登錄不上遠程數據庫服務器,應檢查下賬號是否具有權限,可詢問負責管理測試服務器數據庫管理員。(本人親測不同賬號相同代碼,一個能操作成功一個報錯連接不上數據庫;另,在navicat工具或pycharm ide內配置可視化數據庫時賬號登錄需要使用ssh通道認證,相同的賬號用python代碼連接卻完全不需要ssh遠程連接的代碼,提供賬號和密碼就能登錄成功。數據庫權限限制相關的着實深!)
本次代碼實現連接遠程服務器
由於MySQL服務器以獨立的進程運行,並通過網絡對外服務,所以,需要支持Python的MySQL驅動來連接到MySQL服務器。
目前,MySQL驅動有幾種:
mysql-connector-python:是MySQL官方的純Python驅動;
MySQL-python:是封裝了MySQL C驅動的Python驅動。
安裝MySQL驅動:
pip install mysql-connector-python
測試是否安裝成功,測試python下是否可成功導入mysql.connector即可(import mysql.connector)
pip install MySQL-python (不支持python3)
測試是否安裝成功,測試python下是否可成功導入MySQLdb即可(import MySQLdb)
pip install mysqlclient (mysqlclient 完全兼容MySQLdb,同時支持python3)
測試是否安裝成功,測試python下是否可成功導入MySQLdb即可(import MySQLdb)
pip install PyMySQL
測試是否安裝成功,測試python下是否可成功導入pymysql即可(import pymysql)
python連接MySQL數據庫的多種方式(方式一)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
方式一:
import mysql.connector
打開數據庫連接
db = mysql.connector.connect(host='...',
port=3306,
user='*', # 數據庫IP、用戶名和密碼
passwd='*',
charset = 'utf8')
使用 cursor() 方法創建一個遊標對象 cursor
cursor = db.cursor()
使用 execute() 方法執行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
使用 fetchone() 方法獲取單條數據;使用 fetchall() 方法獲取所有數據
data = cursor.fetchall()
for item in data:
print(item[0])
關閉數據庫連接
db.close()
python連接MySQL數據庫的多種方式(方式二)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
方式二:
import MySQLdb
打開數據庫連接
conn = MySQLdb.connect(host='...',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
使用 cursor() 方法創建一個遊標對象 cursor
cursor = conn.cursor()
使用 execute() 方法執行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
使用 fetchone() 方法獲取單條數據;使用 fetchall() 方法獲取所有數據
data = cursor.fetchall()
for item in data:
print(item)
關閉數據庫連接
cursor.close()
python連接MySQL數據庫的多種方式(方式三)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
方式三:
import pymysql
打開數據庫連接
conn = pymysql.connect(host='...',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
使用 cursor() 方法創建一個遊標對象 cursor
cursor = conn.cursor()
使用 execute() 方法執行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
使用 fetchone() 方法獲取單條數據;使用 fetchall() 方法獲取所有數據
data = cursor.fetchall()
for item in data:
print(item[0])
關閉數據庫連接
cursor.close()
原文地址https://www.cnblogs.com/kristin/p/10718048.html