Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created November 30, 2019 17:38
Show Gist options
  • Save NaniteFactory/9554eb82a88f8d5ecc0a7a76ea5fe1c3 to your computer and use it in GitHub Desktop.
Save NaniteFactory/9554eb82a88f8d5ecc0a7a76ea5fe1c3 to your computer and use it in GitHub Desktop.
go sqlite tutorial example
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "data.db")
if err != nil {
log.Fatalln(err)
}
defer db.Close()
// sql.Open() --> sql.Prepare(), sql.Exec(), sql.Query()
if _, err := db.Exec("CREATE TABLE Test(id INTEGER PRIMARY KEY, t1 TEXT);"); err != nil {
log.Println(err)
}
if _, err := db.Exec(`INSERT INTO Test VALUES (1, "asdf");`); err != nil {
log.Println(err)
}
if _, err := db.Exec(`INSERT INTO Test VALUES (2, "qwer");`); err != nil {
log.Println(err)
}
if _, err := db.Exec(`INSERT INTO Test VALUES (0, "zxcvzxcvxz");`); err != nil {
log.Println(err)
}
rows, err := db.Query("SELECT * FROM Test;")
if err != nil {
log.Println(err)
}
type Record1 struct { // scan to int
id int
t1 string
}
type Record2 struct { // scan to string
id string
t1 string
}
list1 := []Record1{} // scan to int
list2 := []Record2{} // scan to string
for rows.Next() {
// scan to int
row1 := Record1{}
if err := rows.Scan(&(row1.id), &(row1.t1)); err != nil {
log.Println(err)
} else {
list1 = append(list1, row1)
}
// scan to string
row2 := Record2{}
if err := rows.Scan(&(row2.id), &(row2.t1)); err != nil {
log.Println(err)
} else {
list2 = append(list2, row2)
}
}
log.Println(list1) // scan to int
log.Println(list2) // scan to string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment