SQLAlchemy反射:如何查询特定列的数据?

时间:2013-03-05 12:22:12

标签: python mysql sqlalchemy

使用SQLAlchemy反射,如何查询特定列中的数据?

testtable = Table('member', Metadata, autoload=True)

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable).filter_by(is_active=1, is_deleted=0): 
        print(loopCounter + 1, data)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

TestConnection()

上述查询为我提供了成员表中所有列中的所有数据。但我想要的是从列中获取特定数据。例如。我想检索用户名密码列,但我无法正确使用语法。以下是我到目前为止:

def TestConnection():
    loopCounter = 0 
    for password, username in session.query(testtable).filter_by(is_active=1, is_deleted=0):
        print(loopCounter + 1, data)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

失败并出现错误:

Traceback (most recent call last):
File "/home/workspace/upark/src/monitor.py", line 36, in <module>
TestConnection()
File "/home/workspace/upark/src/monitor.py", line 26, in TestConnection
for password, username in session.query(testtable).filter_by(is_active=1, is_deleted=0):
ValueError: too many values to unpack (expected 2)

使用Oracle的Python3.2,SQLAchemy0.8和mysqlconnector。

编辑:稍微进步

刚刚发现我可以在返回所有结果后“过滤”列,如下所示:

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable).filter_by(is_active=1, is_deleted=0): 
        print(loopCounter + 1, data.password, data.username)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")

这将给出:

1 pass1 userone
2 pass2 usertwo

但正如你所看到的那样,那是在我收到所有专栏之后。我想要的只是从我需要的列中获取数据。例如。 Members表有10列。我只需要从其中两个中获取数据以提高效率。

1 个答案:

答案 0 :(得分:2)

只需指定要选择[session.query(testtable.c.password, testtable.c.username)]的列而不是整个表[session.query(testtable)]:

def TestConnection():
    data = None
    loopCounter = 0 
    for data in session.query(testtable.c.password, testtable.c.username).filter_by(is_active=1, is_deleted=0): 
        pwd, usr = data
        print(loopCounter + 1, pwd, usr)
        loopCounter += 1
    if data is None:
        raise Exception ("Could not find any data that matches your query")        
    else:
        print("It worked!")