1

我是一个在表中插入记录的函数,我想获取插入的 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();
        }
4

1 回答 1

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 兼作查询,并返回插入的值。

于 2013-02-13T10:46:46.070 回答