這篇文章給大家介紹如何在python中遠(yuǎn)程連接MySQL數(shù)據(jù)庫(kù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

連接數(shù)據(jù)庫(kù)
這里默認(rèn)大家都已經(jīng)配置安裝好 MySQL 和 Python 的MySQL 模塊,且默認(rèn)大家的DB內(nèi)表和訪問(wèn)賬號(hào)權(quán)限均已設(shè)置無(wú)誤,下面直接代碼演示:
import MySQLdb
import cPickle as pk
def write2file(DB_data,save_filename):
"""數(shù)據(jù)寫入本地"""
with open(save_filename, 'w') as f:
pk.dump(DB_data, f))
# 創(chuàng)建數(shù)據(jù)庫(kù)連接
conn2db = MySQLdb.connect(
host='111.111.111.111',# host
port = 3306, # 默認(rèn)端口,根據(jù)實(shí)際修改
user='username',# 用戶名
passwd='passwd', # 密碼
db ='DBname', # DB name
)
cur = conn2db.cursor() # 操作游標(biāo)
DB_data = cur.execute("select * from table_name;") # SQL語(yǔ)句 ,查詢需要到處內(nèi)容
# 獲取多條數(shù)據(jù)
DB_datas = cur.fetchmany(DB_data)
# 寫入本地
write2file(DB_datas,'save_table_name')
"""
# 打印表中數(shù)據(jù),chek data
for info in DB_datas:
print info
"""
cur.close()
conn2db.commit()
try:
conn2db.close() # 關(guān)閉連接
print "closed connection..."
except Exception,e:
print Exception,":",e關(guān)于如何在python中遠(yuǎn)程連接MySQL數(shù)據(jù)庫(kù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
網(wǎng)站題目:如何在python中遠(yuǎn)程連接MySQL數(shù)據(jù)庫(kù)-創(chuàng)新互聯(lián)
文章源于:http://chinadenli.net/article34/eopse.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)、域名注冊(cè)、定制網(wǎng)站、搜索引擎優(yōu)化、企業(yè)建站、外貿(mào)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容