使用ExecuteScalar插入时,使用Npgsql检索序列ID

Che*_*uis 7 .net c# npgsql

我试图在一个带有串行主键的PostgreSQL表中插入一行,我需要在插入后检索该列.我有这样的事情:

表"pais"有3列:id,pais,capital; id是一个串行列,是它的主键.

NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital)", conn);
query.Parameters.Add(new NpgsqlParameter("nombre", NpgsqlDbType.Varchar));
query.Parameters.Add(new NpgsqlParameter("capital", NpgsqlDbType.Varchar));
query.Prepare();
query.Parameters[0].Value = this.textBox1.Text;
query.Parameters[1].Value = this.textBox2.Text;
Object res = query.ExecuteScalar();
Console.WriteLine(res);
Run Code Online (Sandbox Code Playgroud)

它在表上插入行,但"res"值为null.如果我使用nexval('table_sequence')插入也返回null.

知道怎样才能返回表的id?我错过了什么吗?

提前致谢

hsm*_*ths 16

这个线程安全吗?
如果在插入和选择之间发生了另一次插入怎么办?为什么不使用:

INSERT INTO table (fieldnames) VALUES (values) RETURNING idcolumn

  • 如果select在同一个查询中,那么它是线程安全的,因为它位于同一个"session"中,来自http://www.postgresql.org/docs/8.4/interactive/functions-sequence.html:"因为这是返回一个会话本地值,它提供了一个可预测的答案,无论其他会话是否已经执行了当前会话以来的nextval." (2认同)

小智 10

insert into pais(nombre, capital) values(@nombre, @capital) RETURNING id
Run Code Online (Sandbox Code Playgroud)

替换id为您的主键enter code here并使用

Object res = query.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)

在里面res你会有PK.


Cos*_*lis 6

要选择插入的最后一个标识,您需要使用: currval(sequencename)

所以你的select语句应如下所示:

NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital);select currval('table_sequence');", conn);
Run Code Online (Sandbox Code Playgroud)