# pyDbRowFactory **Repository Path**: harrychinese/pydbrowfactory ## Basic Information - **Project Name**: pyDbRowFactory - **Description**: python db row factory - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2013-06-15 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ###Python版的 DbRowFactory * 介绍: 完成Relational=>Object的单向转换. DbRowFactory 可以将一个entity class 与Python Database API的 cursor (或 SqlAlchemy的 ResultProxy)进行绑定, 绑定后, 可将cursor的row转成绑定类的实例 * 字段匹配规则: DbRowFactory 自动匹配class attribute和 row column_name, 如果你不希望采用这种匹配方式, 可以使用class的setter方法与column_name做匹配 * see: http://www.python.org/dev/peps/pep-0249/ * Tested under: Python 2.7, Jython2.5.2 ###Change log: 1. version 0001, 09 Nov. 2011, initial version 2. version 0002, 16 Feb. 2012, use pyObjectCreator to instantiate rowClass 3. version 0003, 08 Mar. 2012, fromSqlAlchemyResultProxy(), fetchAllRowObjects() functions added 4. version 0004, 31 May. 2013, bug fix version, disable auto-close cursor if not created by SqlAlchemy ###如下是一个示例 ``` ##====================sample begin======= #sample code , file: pkg1.OracleJdbcSample.py from __future__ import with_statement from com.ziclix.python.sql import zxJDBC from pyDbRowFactory import DbRowFactory class rowClass2(object): def __init__(self): self.owner=None self.tablename=None def setOWNER(self, value): self.owner=value def print2(self): print("ownerName="+self.owner+",tablename="+self.tablename) if __name__=="__main__": #DB API 2.0 cursor sample jdbc_url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; username = "user1" password = "pwd1" driver = "oracle.jdbc.driver.OracleDriver" with zxJDBC.connect(jdbc_url, username, password, driver) as conn: with conn.cursor() as cursor : cursor.execute("""select tbl.owner, tbl.table_name tablename, tbl.tablespace_name from all_tables tbl""") #use DbRowFactory to bind rowClass2 class defined in pkg1.OracleJdbcSample.py rowFactory=DbRowFactory(cursor, "pkg1.OracleJdbcSample.rowClass2") for rowObject in rowFactory.fetchAllRowObjects(): rowObject.print2() #sqlalchemy sample from sqlalchemy import create_engine engine=create_engine("sqlite:///:memory:", echo=True) sql="""select tbl.owner, tbl.table_name tablename, tbl.tablespace_name from all_tables tbl""" resultProxy=engine.execute(sql) rowFactory=DbRowFactory.fromSqlAlchemyResultProxy(resultProxy, "pkg1.OracleJdbcSample.rowClass2") for rowObject in rowFactory.fetchAllRowObjects(): rowObject.print2() ```