5

I'm using Visual Studio 2010 PostgreSQL 9.x Npgsql

I'm trying to insert data from fields on a C# WinForms app. I just can't figure out how to generate/retrieve the next primary key value on the fly. Here are my column names:

epiphanyKey [PK] bigserial transaction numeric license character dateOfActv date time time

I need the insert command to be "session-safe" since multiple people could be entering data into the database at the same time.

 NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=password;Database=epiphany;"); // postgres 8.3 on my test system
 conn.Open(); // opens the connection

 NpgsqlCommand cmd = new NpgsqlCommand("INSERT INTO wsmsmrs210 (epiphanyKey,transaction,license,dateOfActv,time, conn);

   NpgsqlDataReader dr = cmd.ExecuteReader();

In the code above the NpgsqlCommand cmd = ... statement doesn't work correctly because I don't know the next primary key value for the primary key value epiphanyKey.

Any ideas or code sniplets to generate the next primary key value when sending the query to the db?

4

2 回答 2

5

您可以使用returning关键字使查询返回刚刚创建的 id。文档中的示例:

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;

您发布的代码不完整,甚至无法编译,因此我无法为您提供如何在您的情况下使用它的完整示例,但这是一个开始:

NpgsqlCommand cmd = new NpgsqlCommand(
  "INSERT INTO wsmsmrs210 " +
  "(epiphanyKey,transaction,license,dateOfActv,time, conn) " +
  "VALUES (...) " +
  "RETURNING epiphanyKey");

int id = cmd.ExecuteScalar();
于 2011-12-02T14:52:04.213 回答
4

插入新对象时,您应该使用序列在数据库中自动生成主 ID。

对于更详细的答案(代码),我需要知道wsmsmrs210表结构。

通常,如果您的数据表是使用以下内容创建的:

CREATE SEQUENCE sequence_name;

CREATE TABLE wsmsmrs210 (
epiphanyKey bigint default nextval('sequence_name'),
...
)

那么您的代码应如下所示:

NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=password;Database=epiphany;"); 
 conn.Open(); // opens the connection

NpgsqlCommand cmd = new NpgsqlCommand("INSERT INTO wsmsmrs210 (transaction,license,dateOfActv,time) VALUES(:a,:b,:c,:d)", conn);
... // add parameters :a, :b, :c, :d via cmd.Parameters.Add(...) here
cmd.ExecuteNonQuery();

// Add next two lines if you need last inserted id in code
cmd = new NpgsqlCommand("SELECT CURRVAL('sequence_name')", conn);
var id = cmd.ExecuteScalar(); 


conn.Close();

如果您想获得最大的可靠性,那么您应该在 PLPGSQL 中编写一个存储函数,该函数将接受您的字段值作为输入参数,将值插入表中,获取最后一个插入 id 并返回它。

于 2011-12-02T14:38:23.717 回答