安装库
1、pymysql :conda install PyMySQL
2、xlrd :conda install xlrd
说明
使用mysql读写云数据,本次测试使用的是阿里云,代码可以通过,亲测有效,写入数据时,首先的在数据库里面新建一个代码中的表,代码才可以跑通,另外推荐一个链接:http://www.runoob.com/python3/python3-mysql.html (链接很详细,要是早发现这个链接也不至于调很久了)。
代码
代码有注释,使用的是Python3。
import pymysql
import xlrd
#读取数据库表格数据存入内存data中
SQL = "SELECT * from user"
db = pymysql.connect("localhost", "root", "0000", "mysql")
cursor = db.cursor()
data = None
try:
cursor.execute(SQL)
data = cursor.fetchall()
except BaseException as e:
print(e)
db.rollback()
print (data[0])
#读取excel数据写入数据库
book = xlrd.open_workbook("students.xls")
sheet = book.sheet_by_name('Sheet1')
query = 'insert into student_tbl (name, sex, minzu, danwei_zhiwu, phone_number, home_number) values (%s, %s, %s, %s, %s, %s)'
for r in range(1, sheet.nrows):
name = sheet.cell(r,0).value
sex = sheet.cell(r,1).value
minzu = sheet.cell(r,2).value
danwei_zhiwu = sheet.cell(r,3).value
phone_number = sheet.cell(r,4).value
home_number = sheet.cell(r,5).value
values = (name, sex, minzu, danwei_zhiwu, phone_number, home_number)
# 执行sql语句
cursor.execute(query , values) #往SQL添加一条数据
print(values)
cursor.close()
db.commit()
db.close()