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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?