I am trying to insert data to a database which I have created using SQLite3
using 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
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")
}