Home > Backend Development > Golang > How to Create MySQL Databases Programmatically using Go\'s `go-sql-driver`?

How to Create MySQL Databases Programmatically using Go\'s `go-sql-driver`?

Barbara Streisand
Release: 2024-12-04 21:52:12
Original
938 people have browsed it

How to Create MySQL Databases Programmatically using Go's `go-sql-driver`?

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)
   }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template