dswqw66280 2018-12-02 23:03
浏览 168

尝试使用Golang插入表格时出现恐慌

I am trying to insert data to a database which I have created using SQLite3using go lang. The database has the name mydb and my table has the name artists and contains 3 cols

Here is my code:

package main

    import (
        "database/sql"
        "fmt"

        _ "github.com/go-sql-driver/mysql"
        sqlite "github.com/mattn/go-sqlite3"
    )

    func main() {
        //create("testdb")
        db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/mydb")
        if err != nil {
            panic(err.Error())
        }
        defer db.Close()

        insert, err := db.Query("INSERT INTO artists (name,album,hits)values('x','y','z')")
        if err != nil {
            panic(err.Error())
        }
        defer insert.Close()
        fmt.Println("connected")
    }

and Here is the error Im getting when i run main.go

  panic: dial tcp 127.0.0.1:3306: connectex: No connection could be made because the target machine actively refused it.

goroutine 1 [running]:
main.main()
        C:/Users/HP/go/src/connectingToDb/main.go:20 +0x1e5
exit status 2

Please note that i have created the database in the same file as the main.go

  • 写回答

1条回答 默认 最新

  • douguizhuang8276 2018-12-03 04:33
    关注

    You should open connect to sqlite like this: db, err := sql.Open("sqlite3", "my.db")

    Here is working code:

    package main
    
    import (
        "database/sql"
        "fmt"
    
        _ "github.com/mattn/go-sqlite3"
    )
    
    func main() {
        db, err := sql.Open("sqlite3", "my.db")
        if err != nil {
            panic(err.Error())
        }
        defer db.Close()
    
        _, err = db.Exec(`CREATE TABLE IF NOT EXISTS artists (`+
             ` id INTEGER PRIMARY KEY AUTOINCREMENT,`+
             ` name text,`+
             ` album text,`+
             ` hits text`+
        `)`)
        if err != nil {
            panic(err.Error())
        }
    
        insert, err := db.Query("INSERT INTO artists (name,album,hits) VALUES('x','y','z')")
        if err != nil {
            panic(err.Error())
        }
        defer insert.Close()
        fmt.Println("connected")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题