Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active May 28, 2024 15:34
Show Gist options
  • Save miguelmota/d54814683346c4c98cec432cf99506c0 to your computer and use it in GitHub Desktop.
Save miguelmota/d54814683346c4c98cec432cf99506c0 to your computer and use it in GitHub Desktop.
Golang SQL insert row and get returning ID example
func InsertOrder(order *Order) (int, error) {
var id int
tx, err := db.Begin()
if err != nil {
return id, err
}
{
stmt, err := tx.Prepare(`INSERT INTO orders(
foo,
bar
) VALUES($1, $2)
RETURNING id`)
if err != nil {
return id, err
}
defer stmt.Close()
err = stmt.QueryRow(
order.Foo,
order.Bar,
).Scan(&id)
if err != nil {
return id, err
}
}
{
err := tx.Commit()
if err != nil {
return id, err
}
}
return id, nil
}
@BigBallard
Copy link

I presume this is for a specific driver and not a general function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment