How to create a new MySQL database with go-sql-driver

后端 未结 3 1589
遇见更好的自我
遇见更好的自我 2020-12-13 11:01

I\'m working on Golang script that automatically clone a database. I\'m using go-sql-driver but i can\'t find in the documentation a way to create a new database. Connection

相关标签:
3条回答
  • 2020-12-13 11:19

    You can perfectly use the go-sql-driver. However, you need to use a mysql user which has the proper access rights to create new databases.

    Here is an example:

    func create(name string) {
    
       db, err := sql.Open("mysql", "admin:admin@tcp(127.0.0.1:3306)/")
       if err != nil {
           panic(err)
       }
       defer db.Close()
    
       _,err = db.Exec("CREATE DATABASE "+name)
       if err != nil {
           panic(err)
       }
    
       _,err = db.Exec("USE "+name)
       if err != nil {
           panic(err)
       }
    
       _,err = db.Exec("CREATE TABLE example ( id integer, data varchar(32) )")
       if err != nil {
           panic(err)
       }
    }
    

    Note that the database name is not provided in the connection string. We just create the database after the connection (CREATE DATABASE command), and switch the connection to use it (USE command).

    Note: the VividCortex guys maintain a nice database/sql tutorial and documentation at http://go-database-sql.org/index.html

    0 讨论(0)
  • 2020-12-13 11:22

    My db_config.go file looks like for GO ORM 2.0:

    package infrastructure
    
    import (
        "fmt"
    
        "gorm.io/driver/mysql"
        "gorm.io/gorm"
        "gorm2.0/utils"
    )
    
    //Setup Models: initializaing the mysql database
    func GetDatabaseInstance() *gorm.DB {
        get := utils.GetEnvWithKey
        USER := get("DB_USER")
        PASS := get("DB_PASS")
        HOST := get("DB_HOST")
        PORT := get("DB_PORT")
        DBNAME := get("DB_NAME")
    
        createDBDsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", USER, PASS, HOST, PORT)
        database, err := gorm.Open(mysql.Open(createDBDsn), &gorm.Config{})
    
        _ = database.Exec("CREATE DATABASE IF NOT EXISTS " + DBNAME + ";")
    
        dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", USER, PASS, HOST, PORT, DBNAME)
        db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    
        if err != nil {
            panic(err.Error())
        }
    
        return db
    }
    
    0 讨论(0)
  • 2020-12-13 11:34

    If you want to create a new database if it does not exist, and use it directly in your program, be aware that database/sql maintains a connection pool.

    Therefore the opened database connection, should preferably contain the database name. I've seen "Error 1046: No database selected" when database/sql opens a new connection after using db.Exec("USE "+name) manually.

    func createAndOpen(name string) *sql.DB {
    
       db, err := sql.Open("mysql", "admin:admin@tcp(127.0.0.1:3306)/")
       if err != nil {
           panic(err)
       }
       defer db.Close()
    
       _,err = db.Exec("CREATE DATABASE IF NOT EXISTS "+name)
       if err != nil {
           panic(err)
       }
       db.Close()
    
       db, err = sql.Open("mysql", "admin:admin@tcp(127.0.0.1:3306)/" + name)
       if err != nil {
           panic(err)
       }
       defer db.Close()
       return db
    }
    
    0 讨论(0)
提交回复
热议问题