1. 安裝MySQL Connector/Python模塊:您可以使用pip命令來安裝MySQL Connector/Python模塊,命令如下:
pip install mysql-connector-python
2. 導(dǎo)入MySQL Connector/Python模塊:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
import mysql.connector
3. 建立與數(shù)據(jù)庫的連接:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
# 配置數(shù)據(jù)庫連接信息 config = { 'host': '遠(yuǎn)程主機地址', 'port': 3306, # MySQL默認(rèn)端口 'user': '用戶名', 'password': '密碼', 'database': '數(shù)據(jù)庫名', 'charset': 'utf8' # 數(shù)據(jù)庫編碼,根據(jù)實際情況設(shè)置 }
# 建立數(shù)據(jù)庫連接文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
cnx = mysql.connector.connect(**config)
在`config`字典中,您需要填寫遠(yuǎn)程主機地址、用戶名、密碼、數(shù)據(jù)庫名等信息。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
4. 創(chuàng)建游標(biāo)對象并執(zhí)行SQL語句:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
# 創(chuàng)建游標(biāo)對象文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
cursor = cnx.cursor()
# 執(zhí)行SQL查詢文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
query = "SELECT * FROM 表名" cursor.execute(query)
# 獲取查詢結(jié)果文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
result = cursor.fetchall()
# 輸出查詢結(jié)果文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
for row in result: print(row)
# 關(guān)閉游標(biāo)文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
cursor.close()
5. 關(guān)閉數(shù)據(jù)庫連接:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
cnx.close()
通過上述步驟,您就可以在Python中實現(xiàn)與異地的MySQL數(shù)據(jù)庫的連接和操作。請確保提供正確的數(shù)據(jù)庫連接信息以及具備訪問遠(yuǎn)程數(shù)據(jù)庫的權(quán)限。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html 文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.ykday.cn/11104.html
評論