Jeff
Jeff

Reputation: 405

Go SQLite3 database connection using sql.Open

I am new to golang and I am a having a hard time connecting to an SQLite3 database hosted on the local machine. I have the SQLite3 database created and have worked through a few tutorials I have fond but they are not working. currently my code is based on another post but I am still unable to make a connection with my database. I believe my problem is in my use of "sql.Open" as I am not clear on the information that I need to provide even after consulting the sql package.

the code builds fine but reports

unable to open database file
error Two tripped

when I try to run the code below

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    _"github.com/mattn/go-sqlite3"
)

func main() {
       
    db, err := sql.Open("sqlite3", "myuser:mypassword@/myDBname") //not clear on what is needed for the user and password
    if err != nil {
        fmt.Println(err)
        fmt.Println("error one tripped")
        return
    }
    defer db.Close()
    err = db.Ping()
    if err != nil {
        fmt.Println(err)
        fmt.Println("error Two tripped")
        return
    }
    fmt.Println("Ping")
    
    return

}

I have not set a username or password for the database I am using, which is hosted on the local machine. I tried several combinations of my computer username/password and no username/password in "sql.Open" but I still have the same problem.

I have installed and imported package code.google.com/p/go-sqlite/go1/sqlite3 and my DB is in the same folder as my Go code.

How do I use make the connection to the SQLite Database? what am I doing wrong with the sql.Open command?

Upvotes: 1

Views: 4822

Answers (1)

Jeff
Jeff

Reputation: 405

For the case when there is no username or password simply put in the full path to the DB including the file name.

ex:

db, err := sql.Open("sqlite3", "/user/home/workspace/myDBname.db")

Upvotes: 3

Related Questions