2016-12-01 24 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 –

相关问题