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
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With