A work encounter problem, insert the contents of the Excel file into the MySQL database.
The general idea is to convert the Excel file to a CSV file-->csv file read--read data into the MySQL database
Use Python's two libraries CSV and MYSQLDB
Here is the specific code:
The database section of the code is not very well documented, specifically documenting the use of the CSV library:
# Insert data from CSV file.
Csv_file = File (' 3d_ptlabs.csv ', ' RB ')
Csv_reader = Csv.reader (csv_file)
Csv_reader generates an iterator that re-creates the contents of the iterator into a list for ease of operation.
rows = [row for row in Csv_reader]
Print Len (rows[0])
Print Rows[0]
1 #Coding:utf-82 3 ImportCSV4 ImportMySQLdb5 6Create_tablesql ="""CREATE TABLE 3DLabInfo (7 UserName VARCHAR () not NULL,8 Platform VARCHAR (Ten),9 Craft VARCHAR (+),Ten OAM VARCHAR (a), One Location VARCHAR (Ten), A voicecardtype VARCHAR (+), - voicecardsn VARCHAR (+), - Intraip VARCHAR (Ten), the pcinternet VARCHAR (+), - Pcdns VARCHAR (+), - signalip VARCHAR (+), - Atesipresource VARCHAR (+), + 3vlanIP VARCHAR (), - H248resource VARCHAR (+), + H248SIGIP VARCHAR (+), A h248numbers VARCHAR (+), at Gatewayuserid VARCHAR (+), - isdnatenum VARCHAR (+), - Comments VARCHAR (a) - )""" -Insert_tablesql ="INSERT into 3DLabInfo (UserName, - Platform, Craft, OAM, location, Voicecardtype, Voicecardsn, Intraip, in pcinternet, Pcdns, Signalip, Atesipresource, 3vlanIP, H248resource, - H248sigip, H248numbers, Gatewayuserid, Isdnatenum, Comments) VALUES" to #Open Mysql Connect +db = MySQLdb.connect ("localhost","","","Test") - thecursor =db.cursor () * #Drop the table if existed. $Cursor.execute ("DROP TABLE IF EXISTS 3DLabInfo")Panax Notoginseng #Create SQL table. - Cursor.execute (create_tablesql) the + A the #Insert data from CSV file. +Csv_file = File ('3d_ptlabs.csv','RB') -Csv_reader =Csv.reader (csv_file) $ $rows = [row forRowinchCsv_reader] - PrintLen (rows[0]) - PrintRows[0] the - forData_listinchRows[1:]:WuyiInsert_sql = Insert_tablesql +Str (tuple (data_list)) the PrintInsert_sql - Try: Wu Cursor.execute (insert_sql) - Db.commit () About except: $ Db.rollback () -Db.close ()
Python inserts a MySQL database from a CSV file