MySQL Register ERROR

Hi,

My Code:


package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"


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

var db *sql.DB

func init() {
	sql.Register("mysql", &mysql.MySQLDriver{})
}

func main() {

	db, err := sql.Open("mysql", "user:password@tcp(xx.xxx.xxx.xxx)/hallo?charset=utf8")
	if err != nil {
		log.Fatal(err)
	}

	var name string
	err = db.QueryRow("select name from users where id = ?", 1).Scan(&name)
	if err != nil {
		log.Fatal(err)
	}
}

error output:

panic: sql: Register called twice for driver mysql

goroutine 1 [running]:
panic(0x826de0, 0xc082005540)
	c:/go/src/runtime/panic.go:481 +0x3f4
database/sql.Register(0x994630, 0x5, 0x1224698, 0xc45ef0)
	c:/go/src/database/sql/sql.go:45 +0x188
....

Why twice?

Importing the mysql library registers it. You’re seeing this error because you’re registering it again. The recommended solution is to import it with a preceding underscore:

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

This registers mysql but prevents “unused import” errors.

1 Like

Thx… :slight_smile:

No problem. I find the whole SQL driver paradigm (the “register-by-import” bit) to be rather unintuitive; fortunately it’s one of those things you run into it once or twice and then learn.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.