Call Postgres SQL stored procedure From Django

2024/9/16 18:23:53

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 procedure from Django 1.5 .. I have written the code but it prompts errors.

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;
BEGININSERT 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;

The Stored Procedure is Ok and it returns results.

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

After all your suggestion my program is finally working. but one small issue left.

As i have used results = c.fetchone() to fetch the out parameters. it returns (13,)

but I only want to get 13 as a string or integer, how can I get only the value.

Updated:

the problem is solved using this

for item in results:message_id = item
Answer
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")

https://en.xdnf.cn/q/72237.html

Related Q&A

How can I mix decorators with the @contextmanager decorator?

Here is the code Im working with:from contextlib import contextmanager from functools import wraps class with_report_status(object):def __init__(self, message):self.message = messagedef __call__(self, …

supervisord always returns exit status 127 at WebFaction

I keep getting the following errors from supervisord at webFaction when tailing the log:INFO exited: my_app (exit status 127; not expected) INFO gave up: my_app entered FATAL state, too many start retr…

One dimensional Mahalanobis Distance in Python

Ive been trying to validate my code to calculate Mahalanobis distance written in Python (and double check to compare the result in OpenCV) My data points are of 1 dimension each (5 rows x 1 column). I…

DeprecationWarning: please use dns.resolver.Resolver.resolve()

I am using resolver() as an alternative to socket() as I found that when multiple connections are made to different IPs it ends up stopping working. Anyway it returns a warning to me that I should use …

python cannot find module when using ssh

Im using python on servers. When I run a python command which needs numpy module, if I do ssh <server name> <python command>that server will complain no module named numpy found.However, if…

Python sklearn installation windows

When trying to install Pythons sklearn package on Windows 10 using pip I am given an EnvironmentError that tells me there is no such file or directory of a specific file: ERROR: Could not install packa…

Python PSD layers?

I need to write a Python program for loading a PSD photoshop image, which has multiple layers and spit out png files (one for each layer). Can you do that in Python? Ive tried PIL, but there doesnt se…

Multiple inheritance: overridden methods containing super()-calls

With the file super5.py:class A:def m(self):print("m of A called")class B(A):def m(self):print("m of B called")super().m()class C(A):def m(self):print("m of C called")supe…

Specifying the output file name in Apache Spark

I have a MapReduce job that Im trying to migrate to PySpark. Is there any way of defining the name of the output file, rather than getting part-xxxxx?In MR, I was using the org.apache.hadoop.mapred.li…

How to plot two DataFrame on same graph for comparison

I have two DataFrames (trail1 and trail2) with the following columns: Genre, City, and Number Sold. Now I want to create a bar graph of both data sets for a side by side comparison of Genre vs. total N…