python 从csv读数据到mysql的实例
如下所示:
import csv import sys,os import MySQLdb def read_csv(filename): with open(filename) as f: f_csv = csv.reader(f) headers = next(f_csv) #数据格式[1111,22222,1111,1111,.....] #for row in f_csv: # Process row # field1=row[1] # ... return headers def conn_to_psto(): #mysql连接方法 #MySQLdb.connect() #postgl连接 onn = MySQLdb.connect(database="testdb", \ user="postgres", \ password="pass123",\ host="127.0.0.1",\ port="5432") cur = conn.cursor() return cur if __name__ == "__main__": #传入文件路径或文件名 filename=sys.argv[1] f_csv=read_csv(filename) cur=conn_to_psto() for row in f_csv: # Process row field1=row[1] ... sql='''insert into .......(field1,field2,...) values(%,%,...) '''.format(field1=field1,field2=field2.........)) cur.execute(sql) conn.commit() conn.close()
以上这篇python 从csv读数据到mysql的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。