简体   繁体   English

python pyscopg2无法从AWS redshift选择数据

[英]python pyscopg2 unable to select data from AWS redshift

I have a postgres database on AWS redshift. 我在AWS redshift上有一个postgres数据库。 Currently I use Python Pyscopg2 to interact with the database. 目前,我使用Python Pyscopg2与数据库进行交互。 I find that I can run: 我发现我可以跑步:

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

but when I do: 但是当我这样做时:

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

what ever I do, it always returns me None Type. 无论我做什么,都会始终返回无类型。 Anyone can give me advice that what is the correct way to interact with redshift postgres? 任何人都可以给我建议,与redshift postgres进行交互的正确方法是什么?

Thank you 谢谢

As required, here's the whole code 根据需要,这是完整的代码

##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'

you missed "fetchall()", when updating - you don't need it, but when selecting - you have to fetch the results http://initd.org/psycopg/docs/cursor.html 您错过了“ fetchall()”,在更新时-您不需要它,但是在选择时-您必须获取结果http://initd.org/psycopg/docs/cursor.html

your code should look like this: 您的代码应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM