String passed into cursor.callproc becomes unknown (psycopg2, python 2.7, postgres 9.3)

落花浮王杯 提交于 2019-12-11 12:24:35

问题


For some reason, passing a string from Python into a Postgres function and calling it using a psycopg2 cursor causes the function to be unrecognized because the argument is unknown.

The function is very simple like so:

CREATE OR REPLACE FUNCTION text_test (some_text text)
RETURNS void AS $$
BEGIN
END;
$$ LANGUAGE plpgsql;

On the python side, I have:

cursor.callproc("text_test", ("test",)) 

And I get the following error:

psycopg2.ProgrammingError: function text_test(unknown) does not exist
LINE 1: SELECT * FROM text_test('test')
                      ^
Hint: No function matches the given name and argument types. You might need to add explicit type casts.

Why does this only happen with strings and what do I need to do to have a function successfully accept a string? For some reason numeric data types are unaffected by this problem.


回答1:


This happens because there is no way to cast the string to the "correct" text type. Is it a char(N)? A varchar(N)? A text?

Unfortunately .callproc() doesn't provide an easy way to specify the argument types but you can always use .execute() casting the arguments explicitly and everything works:

curs.execute("SELECT * FROM text_test(%s::text)", ("test",))



回答2:


You could also make a list with the parameters you need to send:

param_list = ["test"]
curs.callproc(proc_name, param_list)

Here is a good answer about it: python + psycopg2 = unknown types?



来源:https://stackoverflow.com/questions/28409134/string-passed-into-cursor-callproc-becomes-unknown-psycopg2-python-2-7-postgr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!