Reputation: 716
I a function that inserts a record in a table, and i want to get the insered ID. How can I do? I have to make a new query?
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();
}
Upvotes: 1
Views: 4917
Reputation: 2803
Can you try this:
SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
You need to supply the table name and column name of course.
This will be for the current session / connection
http://www.postgresql.org/docs/8.3/static/functions-sequence.html
You can check this also
See the RETURNING clause of the INSERT statement. Basically, the INSERT doubles as a query and gives you back the value that was inserted.
Upvotes: 4