1

Trying to use prepared statements with python's psypcop2 for inserts needs to be setup manually. But using prepared statments with automatic columns such as serial id or timestamps causes errors.

Running sql statements directly via psql:

create table ps_test(
   id serial primary key,
   data text );

prepare pstmt (text) as insert into ps_test values( $1 );

execute pstmt( 'abc' );
execute pstmt( 'def' );

deallocate pstmt;
select * from ps_test;

gives "ERROR: column "id" is of type integer but expression is of type text".

Rewriting the table so that the automatic column is defined last:

drop table ps_test;
create table ps_test (
     data text,
     id serial primary key
);

prepare pstmt (text) as insert into ps_test values( $1 );

execute pstmt( 'abc' );
execute pstmt( 'def' );

deallocate pstmt;
select * from ps_test;

Works.

 data | id 
------+----
 abc  |  1
 def  |  2
(2 rows)

Is there a better way ?

1 Answer 1

1

With standard SQL you would use

INSERT INTO ps_test (data) VALUES ( $1 )

to insert $1 into the data column. Notice the INSERT statement syntax allows for the column_name, data, to be specified in parentheses after the table_name, ps_test.

Therefore, your prepared statement would be

PREPARE pstmt (text) AS INSERT INTO ps_test (data) VALUES ( $1 );
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.