好的,以下是我对SQLAlchemy中插入一行的回答:
在SQLAlchemy中插入一行可以使用session.add()
方法来完成,具体步骤如下:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
email = Column(String)
engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add()
方法插入一行数据:user = User(name='John', age=25, email='john@example.com')
session.add(user)
session.commit()
user = session.query(User).filter_by(name='John').first()
print(user)
完整的代码如下所示:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
email = Column(String)
user = User(name='John', age=25, email='john@example.com')
session.add(user)
session.commit()
user = session.query(User).filter_by(name='John').first()
print(user)
以上代码会在users.db
数据库中插入一行数据,并查询出刚刚插入的数据并打印出来。
算法大赛
云+社区沙龙online [技术应变力]
高校公开课
云+社区沙龙online [新技术实践]
腾讯数字政务云端系列直播
云+社区沙龙online [国产数据库]
领取专属 10元无门槛券
手把手带您无忧上云