目前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)
- #print(User.__table__)
- #print(User.__mapper__)
-
- 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__ #用來獲得Table
- metadata=Base.metadata #獲得MetaDATA
-
- #創建Session並綁定一個數據庫鏈接
- from sqlalchemy.orm import sessionmaker
- from sqlalchemy import engine
- Session=sessionmaker(bind=engine)
-
- #如果沒有數據庫鏈接,可以這樣創建session
- Session=sessionmaker()
-
- #當後來由數據庫鏈接後可以這樣綁定
- Session.configure(bind=engine)
-
-
- ed_user = User('ed', 'Ed Jones', 'edspassword')
- session = Session()
- session.add(ed_user)
- #通過session的add方法添加一個對象
-
-
- from sqlalchemy import *
-
- #our_user = session.query(User).filter_by(name='ed').first()
- #print(ed_user is our_user )
-
- session.add_all([
- User('wendy', 'Wendy Williams','foobar'),
- User('mary', 'Mary Contrary', 'xxg527'),
- User('fred', 'Fred Flinstone','blah')])
-
- session.dirty
- session.new
-
- session.commit()