功能:將Excel數據導入到MySQL數據庫
練習使用sqlite3 將excel的數據導入到mysql
練習sql語句-查看doc
https://docs.python.org/3/lib...
http://www.runoob.com/sqlite/...html
import xlrd import sqlite3 def save_cd_table(): # 建立插入SQL語句 query = '''INSERT INTO orders (job_number, name, section, date, time_in, time_out) VALUES (%s, %s, %s, %s, %s, %s)''' cursor.execute('''CREATE TABLE cd_table(job_number, name, section, date, time_in, time_out)''') # 建立一個for循環迭代讀取xls文件每行數據的, 從第二行開始是要跳過標題 for r in range(1, sheet.nrows): # 關閉遊標 cursor.close() # 提交 database.commit() # 關閉數據庫鏈接 database.close() # 打印結果 print ("") print ("Done! ") print ("") #columns = str(sheet.ncols) #rows = str(sheet.nrows) #print ("我剛導入了 %d columns ",columns ) def read_cd_table(cursor): #t=('10759',) cursor.execute("SELECT * FROM cd_table WHERE job_number =10759 ") result=cursor.fetchall() print(result) #for row in cursor.execute('SELECT * FROM cd_table ORDER by name'): #for row in cursor.execute("SELECT * FROM cd_table WHERE job_number=10759"): # print(row) def main(): # Open the workbook and define the worksheet book = xlrd.open_workbook("CD.xls") #除了sheet_by_index以外還能夠sheet_by_name,另外xlwt的寫操做詞篇暫不贅述 #對於excel的操做有不少有意思的方法,此後會專門寫一篇 sheet = book.sheet_by_index(0) #創建一個MySQL鏈接 database = sqlite3.connect ("mysql_cd.db") # 得到遊標對象, 用於逐行遍歷數據庫數據 cursor = database.cursor() rows = str(sheet.nrows) try: save_cd_table() except : print(".db file is exist") finally: print('out..') read_cd_table(cursor) print(rows) cursor.close() database.close() if __name__ == '__main__': main()