繁体   English   中英

MySQL - 自动创建数据库、表和用户

[英]MySQL - Automate creation of database, tables and user

为了部署应用程序,我需要为基本用户身份验证创建一个数据库。 为了自动化这个过程,我编写了一个 MySQL 批处理文件:

grant all on jetty.* to 'jetty'@'localhost' identified by 'jetty';

create database if not exists jetty;
use jetty;

create table if not exists users
(
  id int unsigned not null auto_increment,
  username varchar(100) not null,
  password binary(60) not null,
  primary key(id),
  unique(username)
);

create table if not exists roles
(
  id int unsigned not null auto_increment,
  role varchar(100) not null,
  primary key(id),
  unique(role)
);

create table if not exists user_roles
(
  user_id int unsigned not null,
  role_id int unsigned not null,
  unique(user_id, role_id),
  index(user_id)
);

insert into users(username, password) values('jetty', $2a$10$YX3cYqn9nHmCOmPZBHXrQ.2nxrktB3CRYG8tXmBmmWvrDKU8uwRSe');

我是第一次这样做,所以我很确定有些事情我可能做错了。 用一个用户填充users表实际上是个好主意吗? 要登录我的应用程序,需要有一些帐户,但我仍然不太确定。

让我烦恼的另一件事是grant声明。 我想知道grant all是否限制性不够。

另外,我是否应该检查要创建的每个表上if not exists

有没有关于批处理脚本的最佳实践?

  1. 使用用户引导数据库是可以的。 如果“码头”离开,请记住更新脚本!
  2. GRANT ALL 不是很严格,这是真的。 锁定得更紧通常是一件好事。
  3. 检查 IF NOT EXISTS 意味着两件事:(a) 如果表已经存在 [good],您的脚本不会失败;(b) 您不会更新现有表 [bad]。 我喜欢 DROP TABLE IF EXISTS 然后创建 TABLE。

不过,请务必在DROP之前备份这些表。

祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM