Skip to content

Cannot switch database with USE command. #173

@ancarda

Description

@ancarda

If I connect to a MySQL server without using the database in the DSN, I am forced to specify the database on every call (SELECT ... FROM database.table). The program below produces this error: Error 1046: No database selected. I clearly selected one using USE. Why do I have to specify the database in the DSN?

What should I do if I need to use multiple databases or need to switch to a different one?

I am using the latest build of both the MySQL driver and Go itself (go1.1.2 darwin/amd64).

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())
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions