Last active
May 28, 2024 15:34
-
-
Save miguelmota/d54814683346c4c98cec432cf99506c0 to your computer and use it in GitHub Desktop.
Golang SQL insert row and get returning ID example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I presume this is for a specific driver and not a general function?