1. 程式人生 > >Python 之 sqlalchemy插入數據

Python 之 sqlalchemy插入數據

process 插入 part mysql ring test size session encoding

表結構:

技術分享圖片

插入數據代碼展示

#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:[email protected]/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()

Python 之 sqlalchemy插入數據