带有自动列的Postgresql准备语句

带有自动列的Postgresql准备语句,postgresql,Postgresql,尝试将准备好的语句与python的psypcop2一起用于插入需要手动设置。但是,将准备好的语句与自动列(如序列id或时间戳)一起使用会导致错误 通过psql直接运行sql语句: create table ps_test( id serial primary key, data text ); prepare pstmt (text) as insert into ps_test values( $1 ); execute pstmt( 'abc' ); execute pstm

尝试将准备好的语句与python的psypcop2一起用于插入需要手动设置。但是,将准备好的语句与自动列(如序列id或时间戳)一起使用会导致错误

通过psql直接运行sql语句:

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;
给出“错误:列“id”的类型为整数,但表达式的类型为文本”

重写表格,以便最后定义自动列:

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;
工作

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

有更好的方法吗?

使用标准SQL

INSERT INTO ps_test (data) VALUES ( $1 )
$1
插入
数据列。请注意,允许在
表名称
ps\u测试
后的括号中指定
列名称
数据

因此,你准备的声明将是

PREPARE pstmt (text) AS INSERT INTO ps_test (data) VALUES ( $1 );

使用标准SQL,您将使用

INSERT INTO ps_test (data) VALUES ( $1 )
$1
插入
数据列。请注意,允许在
表名称
ps\u测试
后的括号中指定
列名称
数据

因此,你准备的声明将是

PREPARE pstmt (text) AS INSERT INTO ps_test (data) VALUES ( $1 );