使用Python實現Excel數據表導入數據庫


import pymysql
import xlrd
from xlrd import xldate_as_tuple
import datetime

# 連接數據庫
try:
db = pymysql.connect(host="192.168.3.xxx", user="root",
passwd="xxxxx",
db="driving_alarms",
charset='utf8')
except:
print("could not connect to mysql server")


def open_excel():
try:
book = xlrd.open_workbook("Lazy.xlsx") # 文件名,把文件與py文件放在同一目錄下
except:
print("open excel file failed!")
try:
sheet = book.sheet_by_name("Byba") # execl里面的Byba
print(sheet)
return sheet
except:
print("locate worksheet in excel failed!")


def insert_deta():
sheet = open_excel()
cursor = db.cursor()
row_num = sheet.nrows
print(row_num)


for i in range(0, row_num): # 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數,所以值是1
row_data = sheet.row_values(i)
print(row_data[0])

date = xldate_as_tuple(row_data[1], 0)
values = datetime.datetime(*date)
print(values)

value = (row_data[0],values, row_data[2],row_data[5])
print(i)

sql = "INSERT INTO driving_role(role_name,create_time,create_by,deleted)VALUES(%s,%s,%s,%s)"
cursor.execute(sql, value) # 執行sql語句
db.commit()
cursor.close() # 關閉連接


open_excel()
insert_deta()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM