diff --git a/go-sql-database/try-sqlite/data/trysqlite.db-shm b/go-sql-database/try-sqlite/data/trysqlite.db-shm deleted file mode 100644 index fe9ac28..0000000 Binary files a/go-sql-database/try-sqlite/data/trysqlite.db-shm and /dev/null differ diff --git a/go-sql-database/try-sqlite/data/trysqlite.db-wal b/go-sql-database/try-sqlite/data/trysqlite.db-wal deleted file mode 100644 index e69de29..0000000 diff --git a/go-sql-database/try-sqlite/main.go b/go-sql-database/try-sqlite/main.go index ccc750c..934bd9f 100644 --- a/go-sql-database/try-sqlite/main.go +++ b/go-sql-database/try-sqlite/main.go @@ -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 + // That’s 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() + }