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 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗