表结构:
![](https://s1.51cto.com/images/blog/201903/12/00cb3081ce9e6814f80d267a62b520f5.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
插入数据代码展示
#Author Kang
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
from sqlalchemy.orm import sessionmaker
#创建对象的基类:
Base = declarative_base()
#定义User对象:
class User(Base):
#表的名字:
__tablename__ = 'user'
#表的结构:
userid = Column(Integer,primary_key=True)
username = Column(String(20))
age = Column(Integer)
department = Column(String(20))
#初始化数据库连接
engine = create_engine("mysql+pymysql://kang:123456@10.3.152.35/test",encoding="utf-8",echo=True)
#创建session类型
DBSession = sessionmaker(bind=engine)
#创建session对象
session = DBSession()
#创建新的user对象
new_user1 = User(username='CC',age=25,department='IT')
new_user2 = User(username="LILI",age=30,department='HR')
new_user3 = User(username='JOHN',age=22,department='IT')
#添加单条数据
#session.add(new_user1)
#添加到session
session.add_all([new_user1,new_user2,new_user3])
#提交即保存到数据库
session.commit()
#关闭session
session.close()