Work with SQLite3 in Go

using github.com/mattn/go-sqlite3.

Photo by Kristaps Ungurs on Unsplash

https://github.com/mattn/go-sqlite3 has more than 4.4k starts at this time. So I think we can count on that 💃.

First to install go-sqlite3 using go-mod

go get https://github.com/mattn/go-sqlite3

Connect and set max_idle_connection (for the case we might use concurrency).

db, err := sql.Open("sqlite3", "path_to_the_db")
if err != nil {

defer db.Close()

defer for close the db after all the around functions finished calling.

Example for query data:

func displayGene(db *sql.DB, ensembleID string) (int, int, int, string, string, string) {
var seqidGene int
var startLocation int
var endLocation int
var sourceGene string
var strandGene string
var attributesGene string

row, err := db.Query("select seqid,start,end, source, strand, attributes from features where featuretype = 'gene' and id = $1;", ensembleID)
if err != nil {
defer row.Close()
for row.Next() { // Iterate and fetch the records from result cursor
var seqid int
var start int
var end int
var source string
var strand string
var attributes string
row.Scan(&seqid, &start, &end, &source, &strand, &attributes)

seqidGene = seqid
startLocation = start
endLocation = end
sourceGene = source
strandGene = strand
attributesGene = attributes

return seqidGene, startLocation, endLocation, sourceGene, strandGene, attributesGene

Here we want to pass parameter to the query, we can use $ for the param.

Use row.Next() to iterate and fetch records from result cursor.

That’s it.

Hope it helps.

Thanks for reading my post.

~~ PEACE~~

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store