2016-12-01 22 views
0

我必須爲一個任務綁定數據庫和編程,我有一個代碼的想法,但需要確保我可以使用我在mySQL中創建的表作爲我的類或Python中的對象。有沒有辦法使用SQL表作爲python中的類或對象?

示例:我使用SQL來創建具有特定地址和郵政編碼的房屋數據庫。一位客戶說他們住在郵政編碼x。我的程序應該通過數據庫解析並返回郵政編碼x內的所有地址。然後理想情況下用SQL結果創建一個SQL表。

不是確切的任務,但它得到了基本的想法。

+0

什麼阻止你實現它?創建一個屬性與表中列相同的類。根據這些值執行查詢。 –

+0

關於第二個想法,我認爲你正在尋找像[SQLAlchemy](http://www.sqlalchemy.org/) –

回答

1

您正在尋找ORM。請參閱SQLAlchemy。例如:

from sqlalchemy import Column, String, Integer, Sequence 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import sessionmaker 


create_session = sessionmaker() 
Base = declarative_base() 


person_autoincr_seq = Sequence('person_autoincr_seq') 

class Person(Base): 
    __tablename__ = "person" 

    id = Column(
     Integer, 
     person_autoincr_seq, 
     server_default=person_autoincr_seq.next_value(), 
     nullable = False, 
     primary_key = True 
    ) 

    name = Column(
     String, 
     nullable = False 
    ) 

    def __init__(self, name,id=None): 
     if id is not None: 
      self.id = id 

     self.name = name 

使用DB:

import logging as log 
from contextlib import closing 


engine = sqlalchemy.engine.create_engine(
    "postgresql://testuser:[email protected]:5432/testdb" 
) 

create_session.configure(bind=engine) 

try: 
    with closing(create_session()) as db_session: 
     name = db_session.query(Person.name).filter_by(id=5).one()[0] 
except Exception: 
    log.exception("Something wrong while querying db") 
+0

的ORM列表與替代python orm解決方案:https://www.fullstackpython.com/object-關係映射器,orms.html –

相關問題