Python SqlAlchemy动态添加数据表字段实例解析

yipeiwu_com7年前Python基础

本文研究的主要是Python SqlAlchemy动态添加数据表字段,具体如下。

我们知道使用SqlAlchemy创建类来映射数据表,类属性等于数据库字段,但有时候要在我们创建表的时候,不确定数据表字段数量,遇到这种情况,应如何解决?

先看常规用法

from sqlalchemy import create_engine,Column,String,Integer
class Mybase(Base):
  #表名
  __tablename__ ='mycars'
  #字段,属性
  myid=Column(String(50), primary_key=True)
  price=Column(String(50))

上述代码是创建mycars数据表,字段分别为myid和price,字段数量是固定,那么要实现动态创建数量不明确的字段,代码如下:

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+pymysql://root:1234@localhost/test?charset=utf8', echo=False)
# engine = create_engine('sqlite:////MyDB.sqlite3', echo=False)
DBSession = sessionmaker(bind=engine)
session = DBSession()
Base = declarative_base()
#定义类
class table_class(Base):
  __tablename__ = 'aaa'
  id=Column(Integer,primary_key=True)

# 动态添加字段
for i in range(3):
  setattr(table_class,'Col'+str(i),(Column('Col'+str(i), String(50),comment='Col'+str(i))))
Base.metadata.create_all(engine)

# 添加数据
dt=table_class(Col1='aaa',Col2="aaa")
session.add(dt)
session.commit()

上述代码可看出,通过使用setattr()来实现动态添加字段,而且字段名可根据实际命名,comment是字段注释,这个只有SqlAlchemy 1.2版本才有的功能 (SqlAlchemy 1.2 安装 :pip install –pre sqlalchemy)

运行结果:

当然,在插入数据和查询数据的时候,会出现无法确定代码中对应字段的属性。可以使用SqlAlchemy执行sql实现插入

总结

以上就是本文关于Python SqlAlchemy动态添加数据表字段实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python使用邻接矩阵构造图代码示例

问题 如何使用list构造图 邻接矩阵的方式 Python代码示例 # !/usr/bin/env python # -*-encoding: utf-8-*- # author:...

python实现泊松图像融合

本文实例为大家分享了python实现泊松图像融合的具体代码,供大家参考,具体内容如下 ``` from __future__ import division import numpy...

浅谈Python peewee 使用经验

本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作。所以,没有使用过 peewee,可以先阅读文档 正确性和覆盖面...

python+mysql实现简单的web程序

这次要为我的python程序加上数据库,主要是实现从mysql中查询出数据并在页面上显示出来。 首先是mysql的配置文件config.py host="127.0.0.1" use...

python 添加用户设置密码并发邮件给root用户

#!/usr/bin/env python #coding: utf8 import os import sys import mkpasswd //这是之前写的,直接调用 impo...