Python如何實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫-創(chuàng)新互聯(lián)

小編給大家分享一下Python如何實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

我們提供的服務(wù)有:成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、憑祥ssl等。為上千余家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的憑祥網(wǎng)站制作公司

主要內(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ù)庫成功!')

以上是“Python如何實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

文章題目:Python如何實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫-創(chuàng)新互聯(lián)
瀏覽地址:http://bm7419.com/article30/dicoso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、品牌網(wǎng)站設(shè)計、服務(wù)器托管、網(wǎng)站設(shè)計、做網(wǎng)站、網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)