import csv
import pymysql
conn = pymysql.connect(host='127.0.0.1',port=3306,user='xx',passwd='xx',db='test',charset='utf8')
print(conn)
cur = conn.cursor()
print(cur)
with open('d:\\tmp\\df.csv') as csvfile:
sp = csv.DictReader(csvfile)
for row in sp:
sql = 'insert into csvtomysql (a,b) values (%d,%d)'%(int(row['a']),int(row['b']))
print(sql)
cur.execute(sql)
conn.commit()
cur.close()
MySQL的建表语句:
create table csvtomysql (a tinyint(4) , b tinyint(4) ) engine=innodb default charset=utf8;
CSV数据:
a | b |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |