从Django调用Postgres SQL存储过程

时间:2015-01-07 12:05:17

标签: python django postgresql stored-procedures

我正在使用Postgres SQL数据库开发Django项目。我写了一个在postgres sql查询上运行完美的商店procdure。

现在我想从django 1.5调用该存储过程..我已经编写了代码,但它会提示错误。

CREATE FUNCTION fn_save_message3(IN msg_sub character varying, IN msg_cont text, IN msg_type character varying, IN msg_category character varying, IN msg_created_by character varying, IN msg_updated_by character varying) RETURNS integer AS
$BODY$ DECLARE msg_id integer := 0;
BEGIN
    INSERT INTO tbl_messages
        (message_subject, message_content, message_type, message_category, 
       created_on, created_by, updated_on, updated_by)
    VALUES 
      (msg_sub, msg_cont, msg_type, msg_category, LOCALTIMESTAMP, 
       msg_created_by, LOCALTIMESTAMP, msg_updated_by);
      Select into msg_id currval('tbl_messages_message_id_seq');
  return msg_id;
END;$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;
ALTER FUNCTION public.fn_save_message(IN character varying, IN text, IN character varying, IN character varying, IN character varying, IN character varying)
  OWNER TO gljsxdlvpgfvui;

存储过程正常,它返回结果。

c = connection.cursor()
    try:
        c.execute("BEGIN")
        c.callproc("fn_save_message", [Message_Subject, Message_Content, Message_Type, Message_Category, Created_By, updated_by])
        results = c.fetchone()
        c.execute("COMMIT")
    finally:
        c.close()
    print results

根据你的所有建议,我的计划终于有效了。但还有一个小问题。

因为我使用results = c.fetchone()来获取out参数。 它返回(13,)

但我只想将 13 作为字符串或整数,我怎样才能获得该值。

更新

使用此

解决问题
for item in results:
        message_id = item

3 个答案:

答案 0 :(得分:4)

c = connection.cursor()
try:
    c.execute("BEGIN")
    c.callproc("fn_save_message3", (Message_Subject, Message_Content, Message_Type, Message_Category, Created_By, Updated_By))
    results = c.fetchall()
    c.execute("COMMIT")
finally:
    c.close()
print results

你忘记了关闭的parens并试图调用cursor上的函数而不是c,并且还有缩进问题。您还应该使用记录为here.

callproc()函数

正如catavaran所说,您应该阅读有关执行自定义SQL的文档并使用占位符。此外,在Django 1.6+中,事务会自动提交,因此不需要c.execute("COMMIT")

答案 1 :(得分:1)

    c = connection.cursor()
    try:
        c.execute("BEGIN")
        c.callproc("fn_save_message3", [Message_Subject, Message_Content, Message_Type, Message_Category, Created_By, updated_by])
        results = c.fetchone()
        c.execute("COMMIT")
    finally:
        c.close()
    for item in results:
        message_id = item

答案 2 :(得分:0)

c.execute("SELECT fn_save_message3(...行缺少右括号。在最后一个引号后添加)

但无论如何,这是从python代码执行SQL的错误方法。您应该使用占位符来防止SQL注入攻击。 Read the documentation以及在django中正确使用SQL的示例。