More useful notes

pull/1/head
Drew Bednar 6 months ago
parent 2f66804bdc
commit 5425bc78bf

@ -94,6 +94,8 @@ func main() {
// If never want to do string concat from user input into a sql statement you run unless you like sql injection attacks
// expects to return one row. If no row it will delay throwing error until Scan is called
row := db.QueryRow("SELECT id, subject, todo FROM todos WHERE id = ?", 1)
// Scan does the heavily lifting for you when casting from db type to go type. It will cast based on the variable type.
// failures of course will be returned as part of the err
err = row.Scan(&id, &subject, &todo)
if err != nil {
log.Fatal(err)
@ -102,13 +104,26 @@ func main() {
log.Printf("id: %d, subject: %s, todo: %s", id, subject, todo)
// This should error on scan
row = db.QueryRow("SELECT * FROM todos WHERE id = ?", 100_000)
err = row.Scan(&id, &subject, &todo)
// We can also use this short hand!
err = db.QueryRow("SELECT * FROM todos WHERE id = ?", 100_000).Scan(&id, &subject, &todo)
if err != nil {
log.Print(err.Error())
}
// There is no row.Close(). Rows objects have a Close() method. No explicit closing required.
//Prepared Queries
// If you will be using the same query over and over you should just prepare the query.
// $N is the postgres query param which SQLite can use too ? is mysql's
//Under the hood, db.Query() actually prepares, executes, and closes a prepared statement
// Thats three round-trips to the database.
stmt, err := db.Prepare("SELECT * FROM todos WHERE id = $N")
if err != nil {
log.Fatal(err)
}
//This prepared statement *sql.Stmt is tied to the database connection from which it was created, and it holds onto that connection until you call stmt.Close()
defer stmt.Close()
}

Loading…
Cancel
Save