【MySQL】重置MySQL的root密碼與修改MySQL默認字符集



第一次在Rails開發中使用MySQL數據庫,結果root密碼也不知道如何安裝的,始終無法登錄root,於是想到重置密碼,在網上找了很多辦法,下面這個是最靠譜的:


新建一個腳本如下:

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# Check if user is root
if [ $(id -u) != "0" ]; then
    printf "Error: You must be root to run this script!\n"
    exit 1
fi

echo "=========================================================================\n"
printf "Reset MySQL root Password for LNMP  ,  Written by Licess \n"
printf "=========================================================================\n"
printf "LNMP is a tool to auto-compile & install Nginx+MySQL+PHP on Linux \n"
printf "This script is a tool to reset mysql root password for lnmp \n"
printf "For more information please visit http://www.lnmp.org \n"
printf "\n"
printf "Usage: sh reset_mysql_root_password.sh\n"
printf "=========================================================================\n"

mysql_root_password=""
read -p "(Please input New MySQL root password):" mysql_root_password
if [ "$mysql_root_password" = "" ]; then
	echo "Error: Password can't be NULL!!\n"
	exit 1
fi

printf "Stoping MySQL...\n"
/etc/init.d/mysql stop
printf "Starting MySQL with skip grant tables\n"
/usr/bin/mysqld_safe --skip-grant-tables >/dev/null 2>&1 &
printf "using mysql to flush privileges and reset password\n"
sleep 10
printf "update user set password = Password('$mysql_root_password') where User = 'root'\n"
/usr/bin/mysql -u root mysql << EOF
update user set password = Password('$mysql_root_password') where User = 'root';
EOF

reset_status=`echo $?`
if [ $reset_status = "0" ]; then
printf "Password reset succesfully. Now killing mysqld softly\n"
killall mysqld
sleep 10
printf "Restarting the actual mysql service\n"
/etc/init.d/mysql start
printf "Password successfully reset to '$mysql_root_password'\n"
else
printf "Reset MySQL root password failed!\n"
fi

其中有些地方需要自己手工修改,例如:

/usr/bin/mysqld_safe --skip-grant-tables >/dev/null 2>&1 &


在我的電腦中輸入命令: whereis mysqld_safe 

結果如下:

mysqld_safe: /usr/bin/mysqld_safe /usr/bin/X11/mysqld_safe /usr/share/man/man1/mysqld_safe.1.gz

所以根據個人情況就修改第31行。

還有一個是第35行,我執行:whereis mysql,結果如下:

mysql: /usr/bin/mysql /etc/mysql /usr/lib/mysql /usr/bin/X11/mysql /usr/include/mysql /usr/share/mysql /usr/share/man/man1/mysql.1.gz


至於MySQL默認字符集的修改如下: 

這裏只考慮linux系統,找到/etc/mysql/my.cnf ,使用root權限打開,

做以下改動:

配置文件中添加如下內容:

[client]
default-character-set=utf8

[mysqld]
character_set_server=utf8
init_connect='SET NAMES utf8'

修改完後,重啓mysql的服務,service mysql restart

使用 mysql> SHOW VARIABLES LIKE 'character%';查看,發現數據庫編碼均已改成utf8。


發佈了114 篇原創文章 · 獲贊 8 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章