使用xlrd模塊
目前xrld最新版為2.0.1,不支持.xls文件,1.2.0版支持.xls文件
pip3 install xlrd == 1.2.0
1、數據庫test中test_excel表,id為自增主鍵
2、F盤中有一張excel表--code_db.xlsx,數據如下
3、通過代碼把表數據插入數據庫中
import xlrd import pymysql # 獲取excel表對象 def open_excel(): try: # 使用xlrd創建一個工作薄對象 table = xlrd.open_workbook(r'F:\code_db.xlsx') except: print("open excel file failed!") try: # 根據工作表的名稱創建表格對象 sheet = table.sheet_by_name('Sheet1') #通過表名稱獲取Sheet對象 return sheet except: print("locate worksheet in excel failed!") # 連接數據庫 def mysql_link(de_name): try: db = pymysql.connect(host="127.0.0.1", user="root", passwd="數據庫密碼", db=de_name, charset='utf8') return db except: print("could not connect to mysql server") db = mysql_link("test") # 從excel表中取數據插入數據庫中 def insert_data(): sheet = open_excel() cursor = db.cursor() #創建游標對象 # sheet.nrows:獲取最大的行數 for i in range(1,sheet.nrows):#第1行是標題名,從第2行開始讀取數據 age = sheet.cell(i,1).value #第i行第2列 name = sheet.cell(i,2).value #第i行第3列 value = (age,name) sql = "insert into test_excel(age,name) values(%s,%s) " cursor.execute(sql,value) db.commit() cursor.close() ''' 數據庫查詢 ''' def search_count(): cursor = db.cursor() select = "select * from test_excel" cursor.execute(select) line_count = cursor.fetchone() print(line_count) #(98, 23, 'ffisf451sfsffssfsf62') insert_data() #插入表數據 search_count() #查詢表數據 db.close() #關閉數據庫連接
結果如下:
注:python連接sql server數據庫
使用pymssql模塊進行連接
#首先根據python版本安裝對應的pymssql import pymssql conn = pymssql.connect(server,user,password,database)