2017-06-01 197 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:完成答案,希望它有幫助 –