2017-06-01 185 views
0

我试图执行一个存储过程来查询一个表,并且无法成功地通过参数传递。使用Python中的参数执行SQL Server存储过程

title=cursor.execute("SELECT titlequery(%s)", str(member_id))` 

titlequery()受此创建:

CREATE OR REPLACE FUNCTION public.titlequery(mid text) 
 
    RETURNS text AS 
 
$BODY$ 
 

 
SELECT title FROM Member WHERE member_id=mid; 
 

 
$BODY$ 
 
    LANGUAGE sql

和错误我得到:

modules.pg8000.core.ProgrammingError: ('ERROR', '42P18', 'could not determine data type of parameter $2', 'postgres.c', '1356', 'exec_parse_message', '', '')

有谁知道这里发生了什么?

+0

'member_id'对象的外观如何? –

+0

这是一个字符串,如'A000042553' –

+0

该查询应该是'cursor.execute(“SELECT titlequery(%s)”%str(member_id))' –

回答

1

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值,而不是价值本身。

此外,我们应该先执行查询,然后使用fetchonefetchmanyfetchall获取其结果,因为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 
+0

谢谢,那帮了我。我现在得到的结果是'[result]'。 '和'符号来自哪里? –

+0

@CallumVanDenHoek:编辑答案,你应该首先执行你的查询,然后用['fetchone'](https://www.python.org/dev/peps/pep-0249/#fetchone)或['fetchmany '](https://www.python.org/dev/peps/pep-0249/#fetchmany)或['fetchall'](https://www.python.org/dev/peps/pep-0249/# fetchall) –

+0

@CallumVanDenHoek:完成答案,希望它有帮助 –