Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection fails with mysql using GoLang

Tags:

mysql

go

I am trying to connect the MySql DB using Go Language and gives me following error.

sql: unknown driver "mysql" (forgotten import?)

My Code

package main

    import (
        "database/sql"
        "fmt"
    )

func main() {
    db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
    checkErr(err);
    err=db.Ping();
}

Also when I import

        _ "github.com/go-sql-driver/mysql"

I am getting error of

imported and not used
like image 711
Mr x Avatar asked Mar 28 '16 04:03

Mr x


People also ask

Why MySQL database is not connecting?

normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server. You should also check that the TCP/IP port you are using has not been blocked by a firewall or port blocking service.

How do I connect to a GO database in MySQL?

Now, let's connect to MySQL. Make sure to create your application in the folder where you've have all your Golang installation files or use commands go mod init test-sql and go mod tidy to create go. mod and go. sum files allowing you to run your Go app in a folder other than the one you've installed Go in.


2 Answers

For others coming to this page as a result of the error sql: unknown driver "mysql" (forgotten import?), the database/sql package must be used in conjunction with a database driver. That means in addition to importing the database/sql package, you need to import a database driver.

For example, for mysql, you could use the package go-sql-driver. Typically, you import this package using the underscore _ notation, meaning it is imported for its side effects only:

import _ "github.com/go-sql-driver/mysql"

You can read more about this and find a list of SQL drivers below:

  • https://golang.org/pkg/database/sql/
  • https://github.com/golang/go/wiki/SQLDrivers
like image 155
Kyle Chadha Avatar answered Oct 27 '22 09:10

Kyle Chadha


Try it again, but look for my NOTEs:

package main

import (
    "database/sql"

    _ "github.com/go-sql-driver/mysql"
)
// NOTE - I removed the import for "fmt" because it was unused.

func main() {
    db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
    checkErr(err);
    err=db.Ping();
    // NOTE - the above line will trigger an error because err is unused.
}

I added the import for the MySQL driver and removed "fmt" because it was unused. This may be the cause of your "imported and not used" error.

like image 11
Surreal Dreams Avatar answered Oct 27 '22 08:10

Surreal Dreams