SQLObject和SQLAlchemy都是Python语言下的ORM(对象关系映射)解决方案,其中SQLAlchemy被认为是Python下事实上的ORM标准。当然,两者都很优秀。
一、安装
将mysql默认存在的test数据库的编码改为utf-8。
uri = r'mysql://root:passwd@127.0.0.1/test?charset=utf8'
sqlhub.processConnection = connectionForURI(uri)
class User(SQLObject):
name = StringCol(length=10, notNone=True)
email = StringCol(length=20, notNone=True)
password = StringCol(length=20, notNone=True)
User.createTable()</div>
运行后,会看到test数据库下出现表user,我们使用show create table user;查看user表的创建语句,结果如下:
三、添加/删除记录
现在我们尝试着添加和删除记录。
运行后,使用select * from user能看到这两个记录:
删除数据
四、查询记录
通过id获取数据:
根据name进行查询:
一对多映射
我们新建一个表,保存user中每个用户的编写的文章:
class Article(SQLObject):
title = StringCol(length=100, notNone=True)
content = StringCol(notNone=True)
user = ForeignKey('User')
Article.createTable()</div>
运行后,使用show create table article查看创建语句:
`content` text NOT NULL,

