Created
May 12, 2022 04:56
-
-
Save nilsmagnus/29f4cf356d450a7cde37523693e95605 to your computer and use it in GitHub Desktop.
Function to return id from postgresql query
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
package pgsql-helper | |
import ( | |
"database/sql" | |
"fmt" | |
) | |
//ExecReturningId executes query and returns id. | |
// The query must specify what field is returned. | |
// Example: | |
// | |
// id, err := ExecReturningId(db, "insert into user(name) values($1) returning id", "Nils Larsgård") | |
// log.Printf("Inserted row with id %d with result %v", id, err) | |
// | |
func ExecReturningId(db *sql.DB, query string, args ...interface{}) (int, error) { | |
id := -1 | |
result, err := db.Query(query, args...) | |
if err != nil { | |
return id, err | |
} | |
if result.Next() { | |
err = result.Scan(&id) | |
if err != nil { | |
return id, err | |
} | |
return id, nil | |
} else { | |
return id, fmt.Errorf("no rows returned from query %q", query) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment