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