小编典典

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

python

使用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()

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

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列。我只需要从其中两个中获取数据即可提高效率。


阅读 150

收藏
2021-01-20

共1个答案

小编典典

只需指定要选择[ 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!")
2021-01-20