2011-05-04 75 views
1

對於部署應用程序,我需要爲基本用戶身份驗證創建一個數據庫。要自動化的過程中,我寫了一個MySQL的批處理文件: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
  1. 自舉你的數據庫與用戶確定。只要記得更新腳本,如果'碼頭'永遠離開!
  2. GRANT ALL並不是很嚴格,這是真的。鎖定更緊密通常是件好事。
  3. 檢查IF NOT EXISTS意味着兩件事情:(1)如果該表已經存在[好]你的腳本將不會失敗,(b)您將不會更新現有的表[衰]。我喜歡DROP TABLE IF EXISTS然後CREATE TABLE。

請確保在DROP之前進行備份。

祝你好運。

+0

,如果你用'DROP TABLE運行,如果EXISTS'選項,那麼請確保它的v.hard安裝應用程序後重新運行該腳本! – 2011-05-04 21:06:19

+0

@詹姆斯C你會建議哪種選擇? – helpermethod 2011-05-04 21:59:47

+1

在開發和測試腳本時,在嘗試創建它之前,有其他命令會使用「DROP」。如果你想在謹慎的方面犯錯(並避免覆蓋東西),那麼我建議你使用命令(因爲你有),如果你試圖在已經存在的數據庫上運行這個「setup」腳本,將會失敗遭到反對。 – 2011-05-05 07:10:25

相關問題