From 1ad41b97767bcb3057eb691ea1a59de8c02bcc1a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 31 Dec 2024 10:48:01 -0600 Subject: [PATCH] Add Connect To A SQLite Database as a Go TIL --- README.md | 3 +- go/connect-to-a-sqlite-database.md | 50 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 go/connect-to-a-sqlite-database.md diff --git a/README.md b/README.md index e2d4654..78eeb42 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1553 TILs and counting..._ +_1554 TILs and counting..._ --- @@ -406,6 +406,7 @@ _1553 TILs and counting..._ - [Build For A Specific OS And Architecture](go/build-for-a-specific-os-and-architecture.md) - [Check If Cobra Flag Was Set](go/check-if-cobra-flag-was-set.md) - [Combine Two Slices](go/combine-two-slices.md) +- [Connect To A SQLite Database](go/connect-to-a-sqlite-database.md) - [Create A Slice From An Array](go/create-a-slice-from-an-array.md) - [Detect If Stdin Comes From A Redirect](go/detect-if-stdin-comes-from-a-redirect.md) - [Deterministically Seed A Random Number Generator](go/deterministically-seed-a-random-number-generator.md) diff --git a/go/connect-to-a-sqlite-database.md b/go/connect-to-a-sqlite-database.md new file mode 100644 index 0000000..eb2f40d --- /dev/null +++ b/go/connect-to-a-sqlite-database.md @@ -0,0 +1,50 @@ +# Connect To A SQLite Database + +Using the `database/sql` module and the `github.com/mattn/go-sqlite3` package, +we can connect to a SQLite database and run some queries. In my case, I have a +SQLite connection string exported to my environment, so I can access that with +`os.Getenv`. It's a local SQLite file, `./test.db`. + +Calling `sql.Open`, I'm able to connect with a SQLite3 driver to the database +at that connection string. The `setupDatabase` function returns that database +connection pointer. Things like `Exec` and `QueryRow` can be called on `db`. I +also need to make sure I close the connection to the database with a `defer`. + +Here is a full example of connecting to a local SQLite database and inserting a +record: + +```go +package main + +import ( + "database/sql" + "fmt" + "os" + + _ "github.com/mattn/go-sqlite3" +) + +func setupDatabase() *sql.DB { + databaseString := os.Getenv("GOOSE_DBSTRING") + if len(databaseString) == 0 { + fmt.Println("Error retrieving `GOOSE_DBSTRING` from env") + os.Exit(1) + } + db, err := sql.Open("sqlite3", databaseString) + if err != nil { + fmt.Printf("Error opening database: %v\n", err) + os.Exit(1) + } + + return db +} + +func main() { + db := setupDatabase() + defer db.Close() + + sql := `insert into users (name) values (?);` + + db.Exec(sql, "Josh") +} +```