一个工作遇到的问题,将excel文件的内容插入到mysql数据库中。
总体思路是 excel文件-->转换成csv文件-->csv文件读取-->读取数据插入mysql数据库
用到python的两个库csv和MySQLdb
下面是具体的code:
代码中数据库部分没啥好记录的,特别记录一下csv库的用法:
# Insert data from csv file.
csv_file = file(‘3D_PTlabs.csv‘, ‘rb‘)
csv_reader = csv.reader(csv_file)
csv_reader生成的是一个迭代器,将迭代器内的内容重新整成list便于操作。
rows = [row for row in csv_reader]
print len(rows[0])
print rows[0]
1 # coding: utf-8 2 3 import csv 4 import MySQLdb 5 6 create_tablesql = """CREATE TABLE 3DLabInfo ( 7 UserName VARCHAR(20) NOT NULL, 8 Platform VARCHAR(10), 9 Craft VARCHAR(20), 10 OAM VARCHAR(20), 11 Location VARCHAR(10), 12 VoicecardType VARCHAR(20), 13 VoicecardSN VARCHAR(20), 14 intraIP VARCHAR(10), 15 PCInternet VARCHAR(20), 16 PCDNS VARCHAR(20), 17 SignalIP VARCHAR(20), 18 ATESipResource VARCHAR(50), 19 3vlanIP VARCHAR(20), 20 H248resource VARCHAR(50), 21 H248SigIP VARCHAR(20), 22 H248Numbers VARCHAR(50), 23 GatewayUserID VARCHAR(50), 24 IsdnAteNum VARCHAR(20), 25 Comments VARCHAR(50) 26 )""" 27 insert_tablesql = " INSERT INTO 3DLabInfo (UserName, 28 Platform, Craft, OAM, Location, VoicecardType, VoicecardSN, intraIP, 29 PCInternet, PCDNS, SignalIP, ATESipResource, 3vlanIP, H248resource, 30 H248SigIP, H248Numbers, GatewayUserID, IsdnAteNum, Comments) VALUES" 31 # Open Mysql connect 32 db = MySQLdb.connect("localhost","","","test") 33 34 cursor = db.cursor() 35 # Drop the table if existed. 36 cursor.execute("DROP TABLE IF EXISTS 3DLabInfo") 37 # Create sql table. 38 cursor.execute(create_tablesql) 39 40 41 42 # Insert data from csv file. 43 csv_file = file(‘3D_PTlabs.csv‘, ‘rb‘) 44 csv_reader = csv.reader(csv_file) 45 46 rows = [row for row in csv_reader] 47 print len(rows[0]) 48 print rows[0] 49 50 for data_list in rows[1:]: 51 insert_sql = insert_tablesql + str(tuple(data_list)) 52 print insert_sql 53 try: 54 cursor.execute(insert_sql) 55 db.commit() 56 except: 57 db.rollback() 58 db.close()