一次Python操作数据库和excel过程
时间:2021-07-01 10:21:17
帮助过:20人阅读
pymysql,xlwt
def sql_into_excel(table_name):
db_info = {
‘user‘:
‘xxx‘,
‘password‘:
‘123456‘,
‘host‘:
‘8.8.8.8‘,
‘db‘:
‘asd‘,
‘port‘: 3306,
‘charset‘:
‘utf8‘,
‘autocommit‘: True}
conn = pymysql.connect(**db_info)
# 建立连接
cur = conn.cursor(pymysql.cursors.DictCursor)
#获取表头的游标
sql =
‘select * from %s‘ %(table_name)
#如果参数在实际查询中需要用‘’,在SQL中写法:‘%s‘
cur.execute(sql)
all =
cur.fetchall()
cur.close()
conn.close()
key =
[]
for i
in all[0]:
key.append(i)
book =
xlwt.Workbook()
sheet = book.add_sheet(
‘sheet1‘)
for j
in range(len(key)):
sheet.write(0,j,key[j])
for x
in range(len(all)):
a =
key[j]
sheet.write(x+1
,j,all[x][a])
book.save(‘test.xls‘)
sql_into_excel(‘table_name‘)
一次Python操作数据库和excel过程
标签:auto mysql code book 连接 使用 脚本 fetch write