Python實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫的方法
本文實例講述了Python實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
主要內(nèi)容:
1、數(shù)據(jù)框數(shù)據(jù)寫入mongdb方法
2、數(shù)據(jù)框數(shù)據(jù)寫入mysql方法
為了以后不重復(fù)造輪子,這里總結(jié)下,如何把數(shù)據(jù)框數(shù)據(jù)寫入mysql和mongodb的方法記錄下來,省得翻來翻去。下面記錄的都是精華。
寫入mongodb代碼片段(使用pymongo庫):
##########################寫入mongodb 數(shù)據(jù)庫###################### ###########################python操作mongodb數(shù)據(jù)庫 from pymongo import MongoClient con=MongoClient() ##連接客戶端 db = con.Class ##創(chuàng)建數(shù)據(jù)庫 post=db.Classdata ##創(chuàng)建集合 ##插入數(shù)據(jù)(df是數(shù)據(jù)框) ##循環(huán)寫入(以字典的方式一條一條插入) for i in range(0,len(df)): u=dict(Class =df.iloc[i,0], Course =df.iloc[i,1],Title=df.iloc[i,7],Section=df.iloc[i,5],Type=df.iloc[i,8], \ Days=df.iloc[i,2],Time=df.iloc[i,6],Room=df.iloc[i,4],Location=df.iloc[i,3],instructors=df.iloc[i,9],status=df.iloc[i,10]) print u post.insert(u)
寫入mysql代碼片段(使用pymysql庫):
##############################寫入mysql數(shù)據(jù)庫################################# import pymysql ## 加上字符集參數(shù),防止中文亂碼 dbconn=pymysql.connect( host="127.0.0.1", database="cgjr", user="root", password="12345", port=3306, charset='utf8' ) # 執(zhí)行sql語句 try: with dbconn.cursor() as cursor: # 執(zhí)行sql語句,插入記錄 sql = 'INSERT INTO t_tao_info (num, price, city, shop_name, title,number,link,sale) VALUES (%s, %s, %s, %s, %s,%s,%s,%s)' for i in range(0,len(data)): print "正在插入數(shù)據(jù):" + str(i) cursor.execute(sql, (data.iloc[i,0], data.iloc[i,1], data.iloc[i,2],data.iloc[i,3],data.iloc[i,4],data.iloc[i,5],data.iloc[i,6],data.iloc[i,7])) # 沒有設(shè)置默認(rèn)自動提交,需要主動提交,以保存所執(zhí)行的語句 dbconn.commit() except dbconn.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) finally: dbconn.close() print ('數(shù)據(jù)已插入,插入數(shù)據(jù)庫成功!')
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》、《Python數(shù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
基于python代碼實現(xiàn)簡易濾除數(shù)字的方法
今天小編就為大家分享一篇基于python代碼實現(xiàn)簡易濾除數(shù)字的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Django模板之基本的 for 循環(huán) 和 List內(nèi)容的顯示方式
這篇文章主要介紹了Django模板之基本的 for 循環(huán) 和 List內(nèi)容的顯示方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python網(wǎng)絡(luò)安全格式字符串漏洞任意地址覆蓋大數(shù)字詳解
這篇文章主要介紹了Python網(wǎng)絡(luò)安全格式字符串漏洞任意地址覆蓋大數(shù)字的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10