SQLAlchemy使用笔记--SQLAlchemy ORM(一)

这篇博客介绍了SQLAlchemy ORM的使用,包括如何创建连接到不同类型的数据库(如postgresql、MySQL等)、建立表、进行基本的CRUD操作。创建 declarative base class 和 User 表,以及如何利用session进行数据插入、更新、读取和删除。示例涵盖了query操作、过滤、别名使用和count、update、delete等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQLAlchemy ORM – Object Relational Tutorial
参考:
http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html

查看版本

>>> import sqlalchemy
>>> sqlalchemy.__version__
'1.0.9'


创建连接

from sqlclachemy import create_engine
engine = create_engine("sqlite:///:memory:", echo=True)

‘sqlite:///:memory:’ 是 database URL

postgresql

sqlalchemy 默认使用 psycopg2

# 默认情况(即使用psycopg2)
engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')

# 使用psycopg2
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')

# 使用pg8000
engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')

MySQL

默认使用mysql-python

# 默认情况(即使用mysql-python)
engine = create_engine('mysql://scott:tiger@localhost/foo')

# 使用mysql-python
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

# 使用MySQL-connector-python
engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')

# 使用OurSQL
engine = create_engine('mysql+oursql://scott:tiger@localhost/foo')

Oracle

默认使用cx_oracle

# 默认情况(即使用cx_oracle)
engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
# 使用cx_oracle
engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')

Microsoft SQL Server

默认使用pyodbc

# 使用pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')

# 使用pymssql
engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')

SQLite

因为sqlite是基于文件的数据库,所以database URL 和前面的不太一样。

# database URL 形式是 sqlite://<nohostname>/<path>
engine = create_engine('sqlite:///foo.db')

# 在Unix/Mac
engine = create_engine(&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值