Sqlachemy是一款开源软件,提供了SQL工具包和ORM对象映射工具,为高效和高性能的数据库访问,实现了完整的企业级持久模型。与hibernate有些相似。通过使用sqlalchemy我们不必写冗长且容易出错的SQL语句,而是通过python对象与数据库进行交互。
首先需要下载sqlalchemy的软件如SQLAlchemy-0.8.1,通过python setup.py install进行安装。
Sqlalchemy分为两大部分,一个是核心SQL语句构造器,一个是SQL对象关系映射,首先我们从基本的SQL工具包开始。
当我们需要与数据库进行交互时,首先需要连接数据库,接着创建表,然后就可以进行添加、删除、修改以及查询表格信息了。下面我们以这样的顺序分别使用SQL和ORM的方法与数据库进行交互。
1.连接数据库
engine = create_engine('sqlite:///D:/SQLite/private/userInfo.db',echo=True)
conn = engine.connect()
2.定义并创建表格
metadata = MetaData()
user_table = Table('user',metadata,
Column('user_id',Integer,primary_key=True),
Column('user_name',String(20)),
Column('user_pwd',String(20))
)
metadata.create_all(engine)
3.添加数据
ins =user_table.insert()
inss = ins.values(user_name='jack',user_pwd='jack123')
conn.execute(inss)
4.查询数据
qr = select([user_table])
rs = conn.execute(qr)
for user in rs:
print user
row = rs.fetchone()
print'user: user_name-'+row['user_name'],'user_pwd-'+row['user_pwd']
rs = conn.execute(select([user_table,user_email]).\
where(and_(user_table.c.user_name.like('j%'),
user_table.c.user_id == user_email.c.user_id,
or_(user_email.c.email_addr.like('%yaho%'),
user_email.c.email_addr.like('%126%')
),
not_(user_table.c.user_id>5)
))
)
order_by()/group_by()/count()
5.修改数据
up = user_table.update().\
where(user_table.c.user_name == bindparam('oldname')).\
values(user_name=bindparam('newname'))
conn.execute(up)
6. 删除数据
dt = user_email.delete().where(user_email.c.email_addr.like('jack%'))
conn.execute(dt)
7.连接查询
jc = user_table.join(user_email)#连接查询,默认以外键作为连接条件
s = select([user_table.c.user_name]).select_from(jc)
conn.execute(s).fetchall()
1. 连接数据库
engine =create_engine('sqlite:///D:/SQLite/private/userInfo.db',echo=True)
2.创建类
Base = declarative_base()
metadata = Base.metadata
class User(Base):
__tablename__ ='userInfo'
user_id = Column(Integer,primary_key = True)
user_name = Column(String(20))
user_pwd =Column(String(20))
def __init__(self,user_name,user_pwd):
self.user_name= user_name
self.user_pwd= user_pwd
def __repr__(self):
return'User<%s,%s>' % (self.user_name,self.user_pwd)
3 创建session
Session = sessionmaker(bind=engine)
session =Session()
1. 添加对象
userIns =User('wendy','wendy111')
session.add(userIns)
session.commit()
2. 查询对象
query =session.query(User)
query=session.query(User.user_name,User.user_pwd).filter(User.user_name.like('%y'))
for instance inquery:
printinstance
print query.all()
#Literal SQL 大部分的字句结构都接受字符串参数
query=session.query(User).filter('user_name=:name').params(name='Wdword').order_by('user_id')
query =session.query(User).from_statement('SELECT user_id,user_name FROM userINfoWHERE user_name like :name').params(name='%y')
3. 修改对象
userIns = session.query(User).filter(User.user_name == 'Mary').first()
userIns.user_name='MaryNew'
session.commit()
4. 删除对象
userIns =session.query(User).filter(User.user_name == 'wendy').first()
session.delete(userIns)
session.commit()
5. 表连接
addr =relationship('Address',backref="users",order_by = "Address.id")
session.query(Address.email_address,User.name).join(User)