我是一个在表中插入记录的函数,我希望得到插入的ID。 我能怎么做?我必须提出新的查询?
using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["AxWaveConnection"].ToString()))
{
conn.Open();
NpgsqlTransaction transaction = conn.BeginTransaction();
String query =
"INSERT INTO Video (youtubeidvideo, title, rating, viewcount, duration, dataadded, errorflag, schedulingflag, schedulingdate, convertdate) " +
"VALUES ('" + youtubeIdVideo + "','" + title + "'," + rating.ToString().Replace(',', '.') + "," + viewCount.ToString() + "," +
duration.ToString() + ", now(), false, false, null, null); ";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn, transaction);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
scopeID = -1; //Duplicate Record
}
transaction.Commit();
conn.Close();
}
答案 0 :(得分:4)
你可以试试这个:
SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
当然,您需要提供表名和列名。
这将是当前的会话/连接
http://www.postgresql.org/docs/8.3/static/functions-sequence.html
您也可以查看
请参阅INSERT语句的RETURNING子句。基本上,INSERT会兼作查询并返回插入的值。