Python的ORM框架SQLObject入门实例

633次阅读  |  发布于5年以前

SQLObject和SQLAlchemy都是Python语言下的ORM(对象关系映射)解决方案,其中SQLAlchemy被认为是Python下事实上的ORM标准。当然,两者都很优秀。

一、安装

复制代码 代码如下:

sudo pip install SQLObject

使用SQLObject操作mysql时候报错ImportError: No module named MySQLdb,那便安装MySQLdb:

复制代码 代码如下:

sudo pip install MySQL-python

没想到又报错了:

复制代码 代码如下:

_mysql.c:29:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

解决方法:

复制代码 代码如下:

sudo apt-get install libmysqlclient-dev python-dev

二、使用其创建表

将mysql默认存在的test数据库的编码改为utf-8。

复制代码 代码如下:

--encoding:utf-8--

from sqlobject import *

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()

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8