简体   繁体   English

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

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

For deploying an application, I'm required to create a database for basic user authentication.为了部署应用程序,我需要为基本用户身份验证创建一个数据库。 To automate the process, I've written a MySQL batch file:为了自动化这个过程,我编写了一个 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');

I've been doing this for the first time, so I'm quite sure there are some things I might not get right.我是第一次这样做,所以我很确定有些事情我可能做错了。 Is it actually a good idea to populate the users table with one user?用一个用户填充users表实际上是个好主意吗? To log into my application, there needs to be some account, still I'm not quite sure.要登录我的应用程序,需要有一些帐户,但我仍然不太确定。

Another thing that bugs me is the grant statement.让我烦恼的另一件事是grant声明。 I wonder if grant all may not be restrictive enough.我想知道grant all是否限制性不够。

Also, should I check for if not exists on every table I'm going to create?另外,我是否应该检查要创建的每个表上if not exists

Are there any best practices concerning batch scripts?有没有关于批处理脚本的最佳实践?

  1. Bootstrapping your database with a user is OK.使用用户引导数据库是可以的。 Just remember to update the script if 'jetty' ever leaves!如果“码头”离开,请记住更新脚本!
  2. GRANT ALL is not very restrictive, that is true. GRANT ALL 不是很严格,这是真的。 Locking down more tightly is usually a good thing.锁定得更紧通常是一件好事。
  3. Checking IF NOT EXISTS means two things: (a) your script won't fail if the table already exists [good] and (b) you won't update an existing table [bad].检查 IF NOT EXISTS 意味着两件事:(a) 如果表已经存在 [good],您的脚本不会失败;(b) 您不会更新现有表 [bad]。 I like to DROP TABLE IF EXISTS and then CREATE TABLE.我喜欢 DROP TABLE IF EXISTS 然后创建 TABLE。

Be sure to make a backup before DROP ing those tables though.不过,请务必在DROP之前备份这些表。

Good luck.祝你好运。

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

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