【问题标题】:python pyscopg2 unable to select data from AWS redshiftpython pyscopg2 无法从 AWS redshift 中选择数据
【发布时间】:2015-01-11 19:45:21
【问题描述】:

我在 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)

无论我做什么,它总是返回我 None 类型。 任何人都可以给我建议,什么是与 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'

【问题讨论】:

    标签: python psycopg2 amazon-redshift


    【解决方案1】:

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

    您的代码应如下所示:

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

    【讨论】:

    • 不,不是这个原因,我试过fechall fechone,curosr总是返回Null,甚至SQL cmd在其他数据库客户端软件中也给了我很多记录
    • 我假设“c.execute”返回None,所以当你尝试运行“c.execute().fetchall() - 它试图在None上找到属性fetchall,你应该首先运行“cursor .execute” 然后是“cursor.fetchall”
    • 来自文档:execute(operation[, parameters]) 准备并执行数据库操作(查询或命令)。参数可以作为序列或映射提供,并将绑定到操作中的变量。变量使用位置 (%s) 或命名 (%(name)s) 占位符指定。请参阅将参数传递给 SQL 查询。该方法返回无。如果执行了查询,则可以使用 fetch*() 方法检索返回的值。
    • 谢谢,我觉得它像 sqlite3,可以自动返回 c.execute() 作为行生成器。
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多