// You don't wait for the garbage collector to do it.
// as long as there’s an open result set (represented by rows), the underlying connection is busy and can’t be used for
//any other query.
//any other query. It's busy because sql.Rows objects don't retrieve all results a query returns. It does it lazily to prevent over runing memory.
// it depends on the driver but there is usually and internal buffer that stores results.
// Also never defer in a loop. Defer only runs on function exit.
deferrows.Close()
@ -114,11 +120,11 @@ func main() {
//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
// $N (e.g. $1, $2, etc...) 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
// That’s three round-trips to the database.
stmt,err:=db.Prepare("SELECT * FROM todos WHERE id = $N")
stmt,err:=db.Prepare("SELECT todo as other_todo FROM todos WHERE id = $1")
iferr!=nil{
log.Fatal(err)
}
@ -126,4 +132,138 @@ func main() {
//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()
deferstmt.Close()
// You can also call with just params the .QueryRow method since the statement is already prepared
varother_todostring
err=stmt.QueryRow(1).Scan(&other_todo)
iferr!=nil{
log.Fatal(err)
}
log.Printf("Other Todo: %s",other_todo)
stmt.Close()
// MODIFYING DATA
// Use db.Exec() with a prepared statement when INSERTING, UPDATING, or DELETING
// Or another statement that doesn't return rows.
stmt,err=db.Prepare("INSERT INTO todos (subject, todo) VALUES ($1, $2)")
iferr!=nil{
log.Fatal(err)
}
deferstmt.Close()
// stmt.Exec returns a sql.Result. That also has access to the statement metadata
// use _ if you don't care about the result and only want to check the err.
// Exec will NOT reserve a connection. unlike db.Query which returns a sql.Rows that
// will hold on to a connection until .Close() is called.