If you want to create a new database if it does not exist and use it directly in your program, keep in mind that database/sql supports connection pooling.
Therefore, an open database connection should preferably contain the database name. I saw "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 }
source share