This post gives an example of Go application which uses SQLite SQL database
engine. We will write a Go program that opens a database, creates a table in
the database, writes some data to the table, and then reads the data from the
table.
Golang provides a generic interface around SQL (or SQL-like) databases [5]. To
use SQLite, we need to install the Go SQLite driver first. We will use the
popular mattn/go-sqlite3 driver in our program. Install the driver by:
$goget-ugithub.com/mattn/go-sqlite3
Source Code
The following is the source code of Go program that uses SQLite (version 3):
packagemylibimport("database/sql"_"github.com/mattn/go-sqlite3")typeTestItemstruct{IdstringNamestringPhonestring}funcInitDB(filepathstring)*sql.DB{db,err:=sql.Open("sqlite3",filepath)iferr!=nil{panic(err)}ifdb==nil{panic("db nil")}returndb}funcCreateTable(db*sql.DB){// create table if not existssql_table:=` CREATE TABLE IF NOT EXISTS items( Id TEXT NOT NULL PRIMARY KEY, Name TEXT, Phone TEXT, InsertedDatetime DATETIME ); `_,err:=db.Exec(sql_table)iferr!=nil{panic(err)}}funcStoreItem(db*sql.DB,items[]TestItem){sql_additem:=` INSERT OR REPLACE INTO items( Id, Name, Phone, InsertedDatetime ) values(?, ?, ?, CURRENT_TIMESTAMP) `stmt,err:=db.Prepare(sql_additem)iferr!=nil{panic(err)}deferstmt.Close()for_,item:=rangeitems{_,err2:=stmt.Exec(item.Id,item.Name,item.Phone)iferr2!=nil{panic(err2)}}}funcReadItem(db*sql.DB)[]TestItem{sql_readall:=` SELECT Id, Name, Phone FROM items ORDER BY datetime(InsertedDatetime) DESC `rows,err:=db.Query(sql_readall)iferr!=nil{panic(err)}deferrows.Close()varresult[]TestItemforrows.Next(){item:=TestItem{}err2:=rows.Scan(&item.Id,&item.Name,&item.Phone)iferr2!=nil{panic(err2)}result=append(result,item)}returnresult}
Now we open database and create a table in our test program. Then write some
data to the table and then read the data from the table.