0

I'm trying to use Python to run a PostgreSQL function that inserts data from one table into another. If I run the function in pgAdmin it works, but if I run it through Python I get the return value, which says it's executed, but it doesn't insert any records.

Here is my Python code

import psycopg2
from parse_config import fn_parse_config

def run_function():

  conn = None
  try:
    # read database configuration
    login_params = fn_parse_config("etl_process.ini", "psycopg_login")
    # connect to the PostgreSQL database
    conn = psycopg2.connect(**login_params)
    # create a cursor object for execution
    cur = conn.cursor()
    # another way to call a stored procedure
    #cur.execute("SELECT * FROM usp_test();")
    cur.callproc('usp_test')
    # process the result set
    row = cur.fetchone()
    while row is not None:
        print(row)
        row = cur.fetchone()
    # close the communication with the PostgreSQL database server
    cur.close()
except (Exception, psycopg2.DatabaseError) as error:
    print(error)
finally:
    if conn is not None:
        conn.close()         
if __name__ == '__main__':
     run_function()

Here is my function

CREATE OR REPLACE FUNCTION usp_test() 
    RETURNS integer AS $$

BEGIN 
INSERT INTO staging_raw_file (Site,
            StyleCode)
        select CAST(a.Site as VARCHAR(10)),
        CAST(a.StyleCode as VARCHAR(30))
from import_raw_file a;

return 5;

END; $$

LANGUAGE plpgsql;

1 Answer 1

2

Found the answer, it needs autocommit setting

conn = psycopg2.connect(**login_params)
conn.autocommit = True

without that it doesn't actually run the insert, but it will return results from just a select without that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.