.Maui Blog

Connect and query to a Sqlite database in Golang

First you need to install the go-sqlite3 library downloadable from Github, github.com/mattn/go-sqlite3

Then copy and adapt the code below to your database.

package main

import (

    "fmt"    
    "database/sql"
    _ "github.com/mattn/go-sqlite3"
    
)

func main() {
    
    db, err := sql.Open("sqlite3", "mydb.db")
    
    if err != nil {
        panic(err)
    }
    
    query_select := "SELECT MAX(id) FROM my_table WHERE id > $1" 
    stmt, err := db.Prepare(query_select)
    
    defer stmt.Close()
    
    if err != nil {
        panic(err)
    }
    
    result := ""
    err = stmt.QueryRow(0).Scan(&result)
    
    if err != nil {
        panic(err)
    }
    
    fmt.Println(result)    

    db.Close()
}
Exit mobile version