如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u013181284/article/details/70173066