未选择Golang MySQL数据库

I'm using github.com/go-sql-driver/mysql package to connect to MySQL. It works well except when I select a database (USE), I can't run queries against it.

package main

import (
    "database/sql"
    "fmt"
    "log"
)

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

func main() {
    dsn := "root:@/"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        fmt.Println("Failed to prepare connection to database. DSN:", dsn)
        log.Fatal("Error:", err.Error())
    }

    err = db.Ping()
    if err != nil {
        fmt.Println("Failed to establish connection to database. DSN:", dsn)
        log.Fatal("Error:", err.Error())
    }

    _, err = db.Query("USE test")
    if err != nil {
        fmt.Println("Failed to change database.")
        log.Fatal("Error:", err.Error())
    }

    _, err = db.Query("SHOW TABLES")
    if err != nil {
        fmt.Println("Failed to execute query.")
        log.Fatal("Error:", err.Error())
    }
}

The program produces this output:

Error 1046: No database selected

Specify the database directly in the DSN (Data Source Name) part of the sql.Open function:

dsn := "user:password@/dbname"
db, err := sql.Open("mysql", dsn)

In your case you need to use transactions:

tx, _ := db.Begin()
tx.Query("USE test")
tx.Query("SHOW TABLES")
tx.Commit()

For SELECT/UPDATE/INSERT/etc need to specify DB name in the query.

That's because db maintains a connection pool that has several connections to mysql database."USE test" just let one connection use schema test. When you do database query later,the driver will select one idle connection,if the connection that use test schema is selected,it will be normal,but if another connection is chosen, it does not use test,so it will report an error:no database selected.

If you add a clause:

db.SetMaxOpenConns(1)

the db will maintain only one connection,it will not have an error.And of course it's impossible in high concurrency scene.

If you specify the database name in sql.open() function,all the connection will use this data base which can avoid this problem.