欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫的方法

 更新時間:2018年04月02日 11:28:24   作者:開心果汁  
這篇文章主要介紹了Python實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫的方法,結(jié)合具體實例形式分析了Python針對mongodb及mysql數(shù)據(jù)庫的連接、寫入等操作實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了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)文章

最新評論