如何用go-sql-driver创建一个新的MySQL数据库 [英] How to create a new MySQL database with go-sql-driver

查看:102
本文介绍了如何用go-sql-driver创建一个新的MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究自动克隆数据库的Golang脚本。
我正在使用go-sql-driver,但在文档中找不到创建新数据库的方法。
连接到MySQL需要一个URL方案,如:

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

但是数据库还没有存在,我只想连接到服务器,然后创建一个新的数据库。



我该怎么做?我必须使用另一个驱动程序?

解决方案

您可以完美地使用go-sql-driver。但是,您需要使用具有适当访问权限的mysql用户来创建新数据库。



以下是一个示例:

  func create(name string){

db,err:= sql.Open(mysql,admin:admin @ tcp(127.0如果错误!=无{
恐慌(错误)
}
推迟db.Close()

_b
$ ,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)
}
}

请注意,连接字符串中未提供数据库名称。我们只是在连接后创建数据库(CREATE DATABASE命令),然后切换连接以使用它(USE命令)。
$ b

注意:VividCortex人员维护一个漂亮的数据库/ sql教程和文档,位于 http://go-database-sql.org/index.html


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?

解决方案

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

这篇关于如何用go-sql-driver创建一个新的MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆