【Python】读取Excel表格动态生成MySQL数据表并插入数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【Python】读取Excel表格动态生成MySQL数据表并插入数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1749字,纯文字阅读大概需要3分钟。
内容图文
![【Python】读取Excel表格动态生成MySQL数据表并插入数据](/upload/InfoBanner/zyjiaocheng/861/00a214476ab948cf9b63d298f7f1309c.jpg)
# coding: utf-8
import pymysql, xlrd
from sqlalchemy import create_engine, Column, Integer, SmallInteger, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
"""
读取Excel动态生成数据表/字段,并插入记录
"""
def make_model(Base, _TABLE_NAME, TABLE_COMMENT):
class table_model(Base):
__tablename__ = _TABLE_NAME
id=Column(Integer,primary_key=True)
# __table_args__ = (Index('index(zone,status)', 'resource_zone', 'resource_status'), # {'comment': '压测资源表'}) # 添加索引和表注释
__table_args__ = ({'comment': TABLE_COMMENT})
return table_model
"""
连接数据库
"""
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1/flasktest", encoding='utf8', echo=True)
"""
读取excel
"""
workbook = xlrd.open_workbook("./table.xls")
sheet = workbook.sheet_by_index(0)
nrows = sheet.nrows
ncols = sheet.ncols
table_name = sheet.cell_value(0,0)
table_comment = sheet.cell_value(0,1)
"""
创建数据表
"""
Base = declarative_base()
table = make_model(Base, table_name, table_comment)
for i in range(0, ncols):
field_name = sheet.cell_value(1, i)
field_type = sheet.cell_value(2, i)
field_comment = sheet.cell_value(3, i).strip().replace('\n', '').replace('\r', '')
print(field_name, field_type, field_comment)
if field_type=="Integer":
setattr(table, field_name, (Column(field_name, Integer, comment=field_comment)))
Base.metadata.create_all(engine)
"""
连接数据表,插入数据
"""
DBSession = sessionmaker(bind=engine)
session = DBSession()
datas = []
for i in range(5, nrows):
data = table()
for j in range(0, ncols):
field_name = sheet.cell_value(1, j)
field_value = sheet.cell_value(i, j)
setattr(data, field_name, field_value)
datas.append(data)
session.add_all(datas)
session.commit()
# show create table xxx;
# 查看带注释的表信息
内容总结
以上是互联网集市为您收集整理的【Python】读取Excel表格动态生成MySQL数据表并插入数据全部内容,希望文章能够帮你解决【Python】读取Excel表格动态生成MySQL数据表并插入数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。