目录
写入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, %s, %s,%s,%s,%s)'for i in range(0,len(data)):
print "正在插入数据:" + 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]))
# 没有设置默认自动提交,需要主动提交,以保存所执行的语句
dbconn.commit()except dbconn.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)finally:
dbconn.close()
print ('数据已插入,插入数据库成功!')
源自:https://blog.csdn.net/u013421629/article/details/78885079