Python實現將資料框資料寫入mongodb及mysql資料庫的方法
阿新 • • 發佈:2020-01-09
本文例項講述了Python實現將資料框資料寫入mongodb及mysql資料庫的方法。分享給大家供大家參考,具體如下:
主要內容:
1、資料框資料寫入mongdb方法
2、資料框資料寫入mysql方法
為了以後不重複造輪子,這裡總結下,如何把資料框資料寫入mysql和mongodb的方法記錄下來,省得翻來翻去。下面記錄的都是精華。
寫入mongodb程式碼片段(使用pymongo庫):
##########################寫入mongodb 資料庫###################### ###########################python操作mongodb資料庫 from pymongo import MongoClient con=MongoClient() ##連線客戶端 db = con.Class ##建立資料庫 post=db.Classdata ##建立集合 ##插入資料(df是資料框) ##迴圈寫入(以字典的方式一條一條插入) 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資料庫################################# import pymysql ## 加上字符集引數,防止中文亂碼 dbconn=pymysql.connect( host="127.0.0.1",database="cgjr",user="root",password="12345",port=3306,charset='utf8' ) # 執行sql語句 try: with dbconn.cursor() as cursor: # 執行sql語句,插入記錄 sql = 'INSERT INTO t_tao_info (num,price,city,shop_name,title,number,link,sale) VALUES (%s,%s,%s)' for i in range(0,len(data)): print "正在插入資料:" + str(i) cursor.execute(sql,(data.iloc[i,data.iloc[i,7])) # 沒有設定預設自動提交,需要主動提交,以儲存所執行的語句 dbconn.commit() except dbconn.Error,e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: dbconn.close() print ('資料已插入,插入資料庫成功!')
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python+MySQL資料庫程式設計入門教程》、《Python數學運算技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。