我正在尝试使用go lang将数据插入使用SQLite3
创建的数据库中。数据库的名称为mydb
,而我的表的名称为Artists,包含3个列
这是我的代码:
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")
}
这是我运行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
请注意,我已经在与main.go相同的文件中创建了数据库
答案 0 :(得分:1)
您应该像这样打开连接到sqlite:
db, err := sql.Open("sqlite3", "my.db")
这是工作代码:
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")
}