Пример #1
0
    def test_addAll(self):
        user1 = User()
        user1.fullname = 'Jon1'
        user2 = User()
        user2.fullname = 'Jon2'

        session.add_all([user1, user2])
        session.commit()
        self.assertIsNotNone(user1.id)
        self.assertIsNotNone(user2.id)

        print(user1, user2)
Пример #2
0
    def test_add(self):
        user = User()
        user.fullname = 'Jon Snow'

        session.add(user)
        session.commit()

        # 如果成功创建用户,id不应该为None
        self.assertIsNotNone(user.id)
        print(user)
Пример #3
0
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from src.model.User import User
"""
这里就很困惑,User是通过什么机制被注册发现的呢?
我只是import了一下啊。。。。。后面也没有显式的使用
"""
"""
驱动引擎
"""
engine = create_engine('mysql+pymysql://root:@localhost:3306/sql_alchemy')

Base = declarative_base()

# 创建表
Base.metadata.create_all(engine)

# 建立一个session
Session = sessionmaker(bind=engine)
session = Session()

# 测试下创建一个用户
if __name__ == '__main__':
    user = User()
    user.fullname = "asdfes"
    session.add(user)
    session.commit()
    print(user.id)