PEP-249指定API用于数据库驱动程序和pg8000
遵循这个API以及
pg8000 is a DB-API 2.0 compatible pure-Python interface to the PostgreSQL database engine.
从PEP-249execute
method specification:
Parameters may be provided as sequence or mapping and will be bound to variables in the operation.
我们可以在pg8000
sources看看如何通过一个例子要查询的参数。
所以你应该通过一个tuple
/list
值,而不是价值本身。
此外,我们应该先执行查询,然后使用fetchone
或fetchmany
或fetchall
获取其结果,因为execute
本身(在sources更多)返回None
。我猜OP需要一个记录,所以我们要使用fetchone
。
注意:fetchone
方法返回的记录表示为tuple
,所以如果我们需要第一个坐标,那么我们应该get it using zero index。
在你的情况,你应该尝试:
parameters = (str(member_id),) # WARNING: don't miss the comma
cursor.execute("SELECT titlequery(%s)", parameters)
title = cursor.fetchone()[0]
或
parameters = [str(member_id)]
cursor.execute("SELECT titlequery(%s)", parameters)
title = cursor.fetchone()[0]
例
这为我工作
import pg8000
table_definition = """
CREATE TABLE Member(
title VARCHAR(40) NOT NULL,
member_id VARCHAR(40) NOT NULL)
"""
procedure_definition = """
CREATE OR REPLACE FUNCTION public.titlequery(mid text)
RETURNS text AS
$BODY$
SELECT title FROM Member WHERE member_id=mid;
$BODY$
LANGUAGE sql
"""
connection = pg8000.connect(database='database',
user='username',
password='password',
host='hostname',
port=5432)
cursor = connection.cursor()
# Preparation
cursor.execute(table_definition)
cursor.execute(procedure_definition)
values = ('Information', 'A000042553')
cursor.execute('INSERT INTO Member (title, member_id) VALUES (%s, %s)',
values)
# Reading stored procedure result
parameters = ('A000042553',)
cursor.execute("SELECT titlequery(%s)", parameters)
title = cursor.fetchone()[0]
print(title)
# Cleanup
cursor.close()
connection.close()
给我们
Information
'member_id'对象的外观如何? –
这是一个字符串,如'A000042553' –
该查询应该是'cursor.execute(“SELECT titlequery(%s)”%str(member_id))' –