Golang MySQL Database Not Selected

Deadly 提交于 2021-01-27 21:22:08

问题


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


回答1:


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)



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/19927879/golang-mysql-database-not-selected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!