Call Postgres SQL stored procedure From Django

前端 未结 3 1180
花落未央
花落未央 2020-12-30 15:22

I am working on a Django Project with a Postgres SQL Database. I have written a stored procedure that runs perfectly on Postgres.

Now I want to call that stored proc

相关标签:
3条回答
  • 2020-12-30 15:28
    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
    

    You forgot the closing parens and were trying to call the functions on cursor instead of c and also had an issue with indentation. You should also use the callproc() function as documented here.

    As catavaran said, you should read the documentation on executing custom SQL and use placeholders. Also, in Django 1.6+, the transactions are commited automatically so there is no need for c.execute("COMMIT")

    0 讨论(0)
  • 2020-12-30 15:42
        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
    
    0 讨论(0)
  • 2020-12-30 15:52

    There is a missing closing parenthesis at the c.execute("SELECT fn_save_message3(... line. Add ) after last quote symbol.

    But anyway it is a wrong method of executing SQL from python code. You should use placeholders to prevent sql injection attacks. Read the documentation with examples of the proper use of SQL in django.

    0 讨论(0)
提交回复
热议问题