Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

go

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 to MySQL require an URL scheme like:

user:password@tcp(localhost:3306)/database_name

But the database not exists yet, I just want to connect to the server and then create a new one.

How can I do that? I have to use another driver?

like image 214
gdg Avatar asked May 14 '15 10:05

gdg


People also ask

How do you create a new database in MySQL?

Open the MySQL Workbench as an administrator (Right-click, Run as Admin). Click on File>Create Schema to create the database schema. Enter a name for the schema and click Apply. In the Apply SQL Script to Database window, click Apply to run the SQL command that creates the schema.

How do I create a GO database?

without database name and run db. Exec("CREATE DATABASE IF NOT EXISTS " + name) . Then close the connection, sql. Open(.../name) with the database name to create a database and use it safely with the pool.


1 Answers

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

like image 136
Didier Spezia Avatar answered Oct 22 '22 21:10

Didier Spezia