python pyscopg2无法从AWS redshift中选择数据

时间:2015-01-11 19:45:22

标签: python psycopg2 amazon-redshift

我在AWS redshift上有一个postgres数据库。目前我使用Python Pyscopg2与数据库进行交互。我发现我可以跑:

curosr.execute("INSERT INTO datatype VALUES (%s, %s)", ("humidity", "some description"))
connect.commit()

但是当我这样做时:

for row in cursor.execute("SELECT * FROM datatype"):
    print(row)

我做什么,总是给我回报无类型。 任何人都可以告诉我与redshift postgres交互的正确方法是什么?

谢谢

根据需要,这是整个代码

##encoding=utf8

from __future__ import print_function
import psycopg2

def connect():
    conn = psycopg2.connect(host = "wbh1.cqdmrqjbi4nz.us-east-1.redshift.amazonaws.com",
                            port = 5439,
                            dbname = "dbname",
                            user = "user",
                            password = "password")
    c = conn.cursor()
    return conn, c

conn, c = connect()

c.execute("INSERT INTO table netatmo VALUES (%s, %s)", (1, 10.5))
conn.commit() # this works, and I can see the data in other db client software

for row in c.execute("SELECT * FROM netatmo").fetchall(): # this not working
    print(row) # AttributeError: 'NoneType' object has no attribute 'fetchall'

1 个答案:

答案 0 :(得分:2)

你错过了" fetchall()", 更新时 - 您不需要它,但在选择时 - 您必须获取结果 http://initd.org/psycopg/docs/cursor.html

您的代码应如下所示:

cursor.execute("SELECT * FROM datatype;")
for row in cursor.fetchall():
    print(row)