第一步:定义一个类,映射DB的一个表,同时要在SQLserver数据库中建立一张对应的表
#Person.py
from sqlalchemy import Column,String,INT
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() #创建对象的基类
class Person(Base): #定义一个类,继承Base
__tablename__='Person'
ID = Column(INT(),primary_key=True)
Name = Column(String(50))
Age = Column(INT())
def __init__(self,name,age):
self.Name=name
self.Age=age
第二步:连接SQLserver,初始化DBsession
#db_mg.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
class DatabaseManagement():
def __init__(self):
self.engine = create_engine('mssql+pymssql://Login:Password@Servername/DBname',echo=True) #初始化数据库连接
DBsession = sessionmaker(bind=self.engine) #创建DBsession类
self.session = DBsession() #创建对象
def add_obj(self,obj): #添加内容
self.session.add(obj)
self.session.commit() #提交
return obj
def query_all(self,target_class,query_filter): #查询内容
result_list = self.session.query(target_class).filter(query_filter).all()
return result_list
def update_by_filter(self, obj, update_hash,query_filter): #更新内容
self.session.query(obj.__class__).filter(query_filter).update(update_hash)
self.session.commit()
def delete_by_filter(self, obj, query_filter): #删除内容
self.session.query(obj).filter(query_filter).delete()
def close(self): #关闭session
self.session.close()
def execute_sql(self, sql_str): #执行sql语句
return self.session.execute(sql_str)
1.create_engine()用来初始化数据库连接,括号内为连接信息:
(“数据库类型+数据库驱动名称://用户名:密码@数据库服务器的名称或IP地址:端口号/数据库名称”)
2.query() 括号内必须是一个类(target_class),如果是对象(obj),需要改为(obj.__class__)
3.filter() 括号内是查询条件,例如:
(and_(Person.Name=="james",Person.Age==18))
第三步:示例
#MyTest.py
from db_mg import DatabaseManagement
from Person import Person
from sqlalchemy import and_
class MyTest():
def __init__(self):
self.db_obj = DatabaseManagement()
def process(self):
person_obj = Person(“james”,18)
person_obj = self.db_obj.add_obj(person_obj)
query_filter=and_(Person.Name=="james",Person.Age==18)
person_list = self.db_obj.query_all(Person, query_filter)
for i in person_list:
print i.Name
if __name__=="__main__":
myTest = MyTest()
myTest.process()