douzhang6496 2016-03-14 01:32
浏览 139

MySQL根据模板数据库创建数据库

I am writing a PHP application which needs to create new databases as data is added. I want a nice and simple way of specifying how the created databases should look like (i.e. what tables they contain, what indices these tables should contain, ...) and this is currently an EER Diagram in MySql Workbench which I then forward engineer onto the server. I do not consider lots of CREATE-statements in PHP code "nice and simple". Triggered by some event in the PHP application I need to do something which creates a new database with a specified name which is a copy of the template database.

This is sorta a duplicate of this question:
MySQL copy/duplicate database
But the answers to that question are not suitable for me.
I do not want to use mysqldump because I cannot take the security risk of executing shell code on the server, which may be vulnerable to code injection as the name of the created database has to be inserted. Also this.
I also do not want to break the database apart with SHOW-statements and manually execute CREATE-statements to stitch together a new database because that becomes cumbersome fast and it may not capture all the aspects of the template database and therefore introduce hard to find bugs. I am also not sure how well this method handles foreign keys when a referencing table is created before the referenced one.

Ideally I'd like to use a simple SQL statement like CREATE DATABASE ? LIKE TemplateDatabase (where ? represents the database name in some form of prepared statement). Unfortunately though it does not seem like that functionality exists in MySQL.
Apparently PostgreSQL can do something like that just fine but I don't want to migrate just because of a single feature.

How can this be accomplished while fulfilling the aforementioned constraints?

  • 写回答

1条回答 默认 最新

  • douche5961 2016-03-14 01:54
    关注

    If your project are new, by correctly well manage migrations, you can separated which part is for table schema, which is for table's data. Copy database is just re-run migration.

    If your project are existed. You can create sql files, and write php scripts to run it manually.

    评论

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元