Home >Backend Development >Golang >Can go-sql-driver Create a New MySQL Database Without a Pre-existing Database Name?
Creating a New MySQL Database with go-sql-driver
In Go, the go-sql-driver package offers a robust way to connect to MySQL databases. However, one common challenge is creating a new database when the connection scheme requires an existing database name.
Can go-sql-driver Create New Databases?
Yes, go-sql-driver can be used to create new MySQL databases. You will need to connect as a MySQL user with the necessary privileges to create new databases.
How to Create a New Database with go-sql-driver:
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 "+databaseName) if err != nil { panic(err) }
_,err = db.Exec("USE "+databaseName) if err != nil { panic(err) }
// For example, create a table named 'example' in the new database _,err = db.Exec("CREATE TABLE example ( id integer, data varchar(32) )") if err != nil { panic(err) }
Important Notes:
The above is the detailed content of Can go-sql-driver Create a New MySQL Database Without a Pre-existing Database Name?. For more information, please follow other related articles on the PHP Chinese website!