Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用sql查询获取列表?_Python_Python 3.x_Postgresql_Psycopg - Fatal编程技术网

如何在python中使用sql查询获取列表?

如何在python中使用sql查询获取列表?,python,python-3.x,postgresql,psycopg,Python,Python 3.x,Postgresql,Psycopg,我在这里定义一个函数并进行查询 def fetch(temp_pass,temp_accno): cur.execute('''SELECT id, name, acc_no, ph_no,address, email,balance FROM accounts WHERE id = %s and acc_no = %s''', (str(temp_pass), str(temp_accno)));

我在这里定义一个函数并进行查询

def fetch(temp_pass,temp_accno):
    cur.execute('''SELECT id, name, acc_no, ph_no,address, email,balance
               FROM accounts
               WHERE id = %s and acc_no = %s''',
            (str(temp_pass), str(temp_accno)));
    row = cur.fetchall()
    print(row[2])
这一行应该是长度为7的列表,但当我运行print(第[2]行)时, 它给我的错误是列表索引超出范围

这是我得到的错误

File "Accounting.py", line 13, in fetch
    print(row[2])
IndexError: list index out of range

行[2]
返回行列表的第三行<代码>行[0][2]返回第一行的第三列

您可以运行这样的代码段来可视化返回的内容:

cur.execute(...)
for row in cur:
    print(row)
row=cur.fetchall()。如果只需要一行,请使用
cur.fetchone()


请注意,查询可能会返回几行,并且不清楚在这种情况下要执行什么操作,因此我将不在这里进行讨论
cur.fetchone()
无论如何只会给您一行。

出于调试目的,您可以尝试打印
行的内容,以确保列表实际包含7个元素。从错误来看,它似乎没有。@TudorPlugaru它只有一个元素,我不知道为什么,因为查询只返回一行。您按id筛选。通常id是唯一字段。您可以执行第[0][2]行操作,以获取已返回的单行的3个字段。如图所示[0][2]效果良好。谢谢,但我还是不明白为什么第[2]排没有工作。现在我明白了,谢谢