-
-
Save ArseniySavin/c3cd68a09869dbc8a1cf3aeee4b3a767 to your computer and use it in GitHub Desktop.
Golang SQL insert row and get returning ID example
This file contains hidden or 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