目前Python 3.x的操作数据库框架比较少,其中Sqlalchemy是一比较优秀的ORM数据持久化操作框架,
它的下载地址为:
http://www.sqlalchemy.org/download.html
目前最新版本为:0.7.3
它不太支持python 3.x,当安装的时候,即使用python setup.py install.会出现
SQLAlchemy includes C extensions which provide an extra speed boost for dealing with result sets. Currently, the
extensions are only supported on the 2.xx series of cPython, not Python 3 or Pypy.
它只是一个警告,并不影响使用,因为它有个2to3.py程序,当版本为python 3.x的时候,它会自动调用的。
安装好以后:
我写了两个测试例子进行测试:
other.py:
- from sqlalchemy import create_engine
- engine=create_engine('sqlite:///:memory:',echo=True)
-
- from sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey
- metadata=MetaData()
-
- users_table=Table('users',metadata,
- Column('id',Integer,primary_key=True),
- Column('name',String),
- Column('fullname',String),
- Column('password',String)
- )
-
- metadata.create_all(engine)
-
- class User(object):
- def __init__(self,name,fullname,password):
- self.name=name
- self.fullname=fullname
- self.password=password
- def __repr__(self):
- return "<User('%s','%s','%s')>" % (self.name,self.fullname,self.password)
-
-
- from sqlalchemy.orm import (mapper, relationship, sessionmaker)
-
-
-
- mapper(User,users_table)
-
- ed_user=User('ed','Ed Jones','edspassword')
- ed_user.password = 'f8s7ccs'
- print(ed_user.fullname)
- print(ed_user.password)
还有一个例子为:
- __author__ = 'minggxu9'
- from sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey
- 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 __init__(self,name,fullname,password):
- self.name=name
- self.fullname=fullname
- self.password=password
- def __repr__(self):
- return "<User('%s','%s','%s')>" % (self.name,self.fullname,self.password)
- users_table=User.__table__
- metadata=Base.metadata
-
-
- from sqlalchemy.orm import sessionmaker
- from sqlalchemy import engine
- Session=sessionmaker(bind=engine)
-
-
- Session=sessionmaker()
-
-
- Session.configure(bind=engine)
-
-
- ed_user = User('ed', 'Ed Jones', 'edspassword')
- session = Session()
- session.add(ed_user)
-
-
-
- from sqlalchemy import *
-
-
-
-
- session.add_all([
- User('wendy', 'Wendy Williams','foobar'),
- User('mary', 'Mary Contrary', 'xxg527'),
- User('fred', 'Fred Flinstone','blah')])
-
- session.dirty
- session.new
-
- session.commit()