Ubuntu中MySQL安裝與使用筆記 mysql安裝 $ sudo apt-get install mysql-server mysql-client mysql服務器啟動、關閉和重啟 $ sudo /etc/init.d/mysql start/stop/restart 設置初始密碼 $ mysqladmin -u root -p password 你的密碼 修改密碼 $ mysqladmin -u root -p password 你的新密碼 (終端會提示輸入原始密碼) Enter password: mysql登錄本地服務器(例如登錄root用戶) $ mysql -uroot -p 或者: Enter password: $ mysql -hlocalhost -uroot -p mysql登錄遠程服務器(例如登錄root用戶) $ mysql -h hostname/ip -P portnum -uroot -p Enter password: 注意-P(大寫)指定端口號,該參數可以省略,省略後將連接默認端口3306. 創建新用戶及設置權限(GRANT命令) GRANT可以用來創建用戶並同時設置權限,也可以對已有用戶設置或者修改權限,使用方法相似,GRANT的格式如下: grant <privileges> on 數據庫對象(database.table) to 用戶(user@host) [IDENTIFIED BY "<password>"] [WITH GRANT OPTION]; (1)如果指定了IDENTIFIED BY "<password>",如果user@host不存在則該命令將創建一個新用戶並指定權限<privileges>,如果user@host存在則該命令將指定權限<privileges>,若密碼與原始密碼不一致,還會修改成新的密碼。因此指定了IDENTIFIED BY,GRANT可以創建用戶、修改密碼、指定權限等; (2)如果沒有指定IDENTIFIED BY,GRANT可以用來指定權限,也就是設置或者修改權限是不用指定密碼的; (3)<privileges>字段可以指定為"ALL PRIVILEGES"表示所有權限,或者其他指定的多個以逗號隔開的權限字段; (4)database.table字段表示某個數據庫的某個表,*.*表示所有的數據庫的所有表,dbname.*表示數據庫dbname的所有表; (5)user@host字段表示host主機上的user用戶,user@localhost表示user用戶只能從本地訪問,user@"%"表示user用戶可以從任意主機訪問,user@'192.168.0.1'表示用戶user只能從指定主機訪問。 例子: For creating a new user with all privileges (use only for troubleshooting), at mysql prompt type: $ mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourusername'@'localhost' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION; For creating a new user with fewer privileges (should work for most web applications) which can only use the database named "database1", at mysql prompt type: $ mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON database1.* TO 'yourusername'@'localhost' IDENTIFIED BY 'yourpassword'; yourusername and yourpassword can be anything you like. database1 is the name of the database the user gets access to. localhost is the location which gets access to your database. You can change it to '%' (or to hostnames or ip addresses) to allow connections from every location (or only from specific locations) to the database. Note, that this can be a security problem and should only be used for testing purposes! 【關於GRANT的詳細用法可以從網上查看相關資料】 查看用戶權限 $ mysql> show grants for user@host; $ mysql> show grants for user; 等價於:$ mysql> show grants for user@"%";