douzhongju8780 2015-05-25 16:31
浏览 256
已采纳

使用sql.Open进入SQLite3数据库连接

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?

</div>
  • 写回答

1条回答 默认 最新

  • douhui3760 2015-05-28 12:56
    关注

    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")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog