pymsql批量导入数据库

2019年5月7日19:14:12 发表评论 1,055 views

今天做了一个批量导入数据库的玩意,日后有用:

import pymysql
db_config = {
    'host':'127.0.0.1',
    'port':3306,
    'user':'root',
    'password':'qwe123',
    'db':'testconn',
    'charset':'utf8'
}
conn = pymysql.connect(**db_config)
cur = conn.cursor()
f = open('newwrite.csv','r',encoding='gbk')
ss = f.readlines()
# print(ss)
for i in range(10):
    dd = ss[i].split(',')
    # print(dd)
    if len(dd) == 7:
        # print(dd)
        dd[-1] = dd[-1].replace('\n','')
        sql = "insert into test190506 values('%d','%s','%s','%d','%s','%s')"%(int(dd[0]),dd[1],dd[2],int(dd[3]),dd[4],dd[5])
        cur.execute(sql)
        conn.commit()
sql2 = 'select * from test190506'
cur.execute(sql2)
print(cur.fetchall())
cur.close()
conn.close()
f.close()

#注意插入数据的长度和表的类型长度对应,数据的格式要对应表的格式,最后关闭游标连接和文件

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: