Creating MySQL Databases with go-sql-driver
Despite go-sql-driver's functionality, it lacks explicit documentation on database creation. Nevertheless, your database schema can be separated from its creation by utilizing a database user with adequate privileges.
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) } }
In this example, the database name is absent in the connection string. The database is created after establishing the connection via the CREATE DATABASE command. The connection is then switched to the newly created database using the USE command.
Refer to the database/sql tutorial and documentation at http://go-database-sql.org/index.html for further guidance on database interactions in Golang.
The above is the detailed content of How to Create MySQL Databases Programmatically using Go\'s `go-sql-driver`?. For more information, please follow other related articles on the PHP Chinese website!