一:连接MySQL数据库
首先导入模块:pymysql--> pip install pymysql
数据库连接步骤:
1.导包 import pymysql 2.打开数据库连接 db = pymysql.connect('localhost','用户名','密码','数据库名称') 3.使用cursor()方法创建一个游标 cursor = db.cursor() 4.使用execute()执行SQL查询 cursor.execute('select version()') 5.使用fetchone()方法获取单条数据 data = cursor.fetchone() 6.关闭数据库连接 db.close()
二:读取Excel表格,并导入到MySQL数据库
首先介绍使用的xlrd模块:
Excel操作主要用到两个模块,xlrd读取Excel,xlwt写Excel
#导入模块 import pymysql import xlrd #获取表格数据 data = xlrd.open_workbook('xls路径') #按照下标获取 table = data.sheet_by_index(0) lines = table.nrows cols = table.ncols #1.打开数据库的连接 conn = pymysql.connect( host = 'localhost', user = 'root', password = 'root', db = 'cesi', port = 3306, charset = 'utf-8', ) #2.创建一个游标对象 cur = conn.cursor() #3.sql语句 query = 'insert into db_cesi'(time,price,sale,profit)values("%s","%s","%s","%s") for i in range(1,lines): #在此处获取的时间信息方法 time xlrd.xldate.xldate_as_datetime(table.cell(i,0).value,0) price = table.cell(i,1).value sale = table.cell(i,2).value profit = table.cell(i,3).value values = (time,price,sale,profit) #4.执行sql语句 cur.execute(query%values) #5.关闭游标 cur.close()
#提交到数据库执行
conn.commit()
#6.关闭数据库 conn.close()
操作Excel的步骤详解:
table = data.sheets()[]
table = data.sheet_by_index(sheet_index)
table = data.sheet_by_name(sheet_name)
三种获取数据的方式依次为:通过索引顺序获取,通过索引顺序获取,通过名称获取
读取时间的方式:time = xlrd.xldate.xldate_as_datetime(table,cell(x,y).value,0)