Reputation: 680
I have a c script which writes incoming aircraft data to a postgres db. I would like to return the new records ID after the INSERT but am having trouble.
The simplified code is like this:
int new_id;
conn = PQconnectdb("dbname = flight_dev");
PQinitTypes(conn);
PGresult *res = PQexecf(conn,"INSERT INTO aircrafts (hex) VALUES (%text)", aircraft_hex);
PQgetf(res, 0, "%int4", 0, &new_id);
The INSERT is successful however new_id is not assigned and gives the error "row number 1 is out of range 0..-1"
Any help would be great thanks.
Upvotes: 2
Views: 672
Reputation: 680
I had been missing the semicolon when previously using RETURNING id
PGresult *res = PQexecf(conn,"INSERT INTO aircrafts (hex) VALUES (%text) RETURNING ID;", aircraft_hex);
Upvotes: 2
Reputation: 945
use INSERT INTO aircrafts (hex) VALUES (%text) RETURNING id
to return the id column of the newly inserted row
Upvotes: 3