首页 技术 正文
技术 2022年11月16日
0 收藏 733 点赞 4,449 浏览 1393 个字

创建连接


# 参数: '数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test')# sqlite 是文件数据库,连接方式不同
# sqlite://<nohostname>/<path>
engine = create_engine('sqlite:///foo.db')# Unix/Mac
engine = create_engine('sqlite:////absolute/path/to/foo.db')# windows
engine = create_engine(r'sqlite:///C:\path\to\foo.db')
engine = create_engine('sqlite:///C:\\path\\to\\foo.db')

表的创建

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()class User(Base):
__tablename__ = 'users' id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String) def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password) # 创建表
Base.metadata.create_all(engine)

CRUD

创建 session

from sqlalchemy.orm import sessionmakerDBSession = sessionmaker(bind=engine)
session = DBSession()

插入数据

# 插入单条记录
ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)# 插入多条记录
session.add_all([
User(name='wendy', fullname='Wendy Williams', password='foobar'),
User(name='mary', fullname='Mary Contrary', password='xxg527'),
User(name='fred', fullname='Fred Flinstone', password='blah')])# 提交到数据库
session.commit()# 如果想要操作只是在内存中,不真正commit,ed_user.id 不为None,可以使用flush操作,它只是写到内存中
session.flush()

更新

user.name = 'haha'
session.commit()

删除

session.delete(user)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,953
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,478
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,290
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,107
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,739
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,773