普通网友 2015-05-14 10:29
浏览 251
已采纳

如何使用go-sql-driver创建新的MySQL数据库

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?

  • 写回答

2条回答 默认 最新

  • dsfgdsjfd78773 2015-05-14 11:48
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误