举 2018-06-21
如下所示:
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()