我正在尝试将一行插入到具有串行主键的 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);
它在表中插入行,但“res”值为空。如果我使用 nexval('table_sequence') 插入也返回 null。
知道如何返回表的 ID 吗?我错过了什么吗?
提前致谢
最佳答案
那个线程安全吗?
如果在插入和选择之间发生另一个插入怎么办?
为什么不使用:
INSERT INTO table (fieldnames) VALUES (values) RETURNING idcolumn
?
关于c# - 使用 ExecuteScalar 插入时使用 Npgsql 检索序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5583517/