Sqlx: Retrieve ID from insert to DB

Created on 8 Sep 2014  路  4Comments  路  Source: jmoiron/sqlx

Hi!

I have this insert into the database:

user := new(User)
res, err := db.NamedExec("INSERT INTO users (email) VALUES (:email) RETURNING id", user)

And I'd like to get the ID of that record. I believe I'm using the RETURNING id incorrectly. Is this the correct way to do it via db.NamedExec? If not, what are the proper ways to do so?

Thanks!
@luiscvega

Most helpful comment

Hi Luis,

Try using NamedQuery instead and scanning the resulting rows:

var id int
var user User
rows, err := db.NamedQuery("INSERT INTO users (email) VALUES (:email) RETURNING id", user)
// handle err
if rows.Next() {
    rows.Scan(&id)
}

You could also use a prepared named statement which you can then use Get with.

Hope this helps!

All 4 comments

Hi Luis,

Try using NamedQuery instead and scanning the resulting rows:

var id int
var user User
rows, err := db.NamedQuery("INSERT INTO users (email) VALUES (:email) RETURNING id", user)
// handle err
if rows.Next() {
    rows.Scan(&id)
}

You could also use a prepared named statement which you can then use Get with.

Hope this helps!

Thanks jmoiron! Really great job, especially with http://go-database-sql.org!

@jmoiron Hi
When the insert fails you still get the id returned. err is also nil.
How can you tell if the insert was not successful (e.g. due to a foreign key constraint)?

@jmoiron I am running into the same issue as @dontogbe - I am using NamedQuery() to insert values into a table such that a foreign key constraint is violated.

However, the error returned by NamedQuery() is nil, and the issue can only be caught when the transaction is being committed.

Is there a way for us to catch this error sooner?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MichaelHipp picture MichaelHipp  路  5Comments

davisford picture davisford  路  5Comments

plandem picture plandem  路  5Comments

ARolek picture ARolek  路  5Comments

huygn picture huygn  路  6Comments