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()