alchemy | 英[ˈælkəmi] | 美[ˈælkəmi] |
n. | 炼金术; 炼丹术; (改变事物、物质的)魔力(或方法) ; (事物、物质的) 神秘变化; |
SQLAlchemy是Python中最有名的ORM框架(Object-Relational Mapping,把关系数据库的表结构映射到对象上。)
连接示例文件:
1 #coding:UTF-8 2 from sqlalchemy import Column,String,create_engine 3 from sqlalchemy.orm import sessionmaker 4 from sqlalchemy.ext.declarative import declarative_base 5 import MySQLdb 6 7 #创建对象的基类: 8 Base = declarative_base() 9 #定义user对象 10 class User(Base): 11 __tablename__ = 'user' 12 #表的结构 13 id = Column(String(20), primary_key=True) 14 username = Column(String(20)) 15 #初始化数据库连接 16 #db = SA.create_engine( 17 # "mysql://%s:%s@%s/%s?charset=utf8" % (db_info["user"], db_info["password"], db_info["host"], db_info["db_name"]), 18 engine = create_engine("mysql://%s:%s@%s/%s" % ("root","1111", "localhost", "test" )) 19 #engine = create_engine('mysql://root:1111@localhost/test') 20 #创建DBsession类型: 21 DBSession = sessionmaker(bind=engine) 22 23 #创建session 24 session = DBSession() 25 #创建Query查询,filter是where查询条件,最后调用one()返回唯一行,如果调用all()就返回所有行 26 user = session.query(User).filter(User.id==9).one() 27 auser = session.query(User).filter().all() 28 #打印类型和对象的name属性 29 print 'type==',type(user),",username:",user.username 30 for i in auser: 31 print i.id,"username:",i.username 32 #关闭session 33 session.close()
一个简易的demo