通過shell腳本對mysql的增刪改查及my.cnf的配置
shell操作mysql
1.獲取mysql默認密碼
新安裝的mysql,密碼是默認密碼
#!/bin/bash # STRING:獲取mysql默認密碼的一段字符串 # 例如:A temporary password is generated for root@localhost: xxxxxx # PASSWORD:將獲取到的STRING進行截取,獲取localhost:右邊的默認密碼 # shellcheck disable=SC2006 STRING=`grep "temporary password" /var/log/mysqld.log` PASSWORD=${STRING#*localhost: }
若已經(jīng)修改了密碼的
#!/bin/bash # shellcheck disable=SC2006 PASSWORD="你的密碼"
2.修改my.cnf文件
原因:在mysq5.6還是5.7以上,使用如下的shell腳本進行連接,會提示在命令行輸入密碼不安全。
mysql -u root -pPASSWORD -e "xxxxxx"
解決方法:使用sed命令在my.cnf文件中添加如下字段
[client] user=root password=xxxxxx
shell腳本:
# 我的my.cnf文件在/etc/my.cnf下,不相同的可以自己去找找 # sed -i '第幾行 添加的內容' 指定的文件 sed -i '1i [client]' /etc/my.cnf sed -i '2i user=root' /etc/my.cnf sed -i '3i password=xxxxxx' /etc/my.cnf
3.shell創(chuàng)建mysql數(shù)據(jù)庫
# SQL語句 DATABASE_SQL="CREATE DATABASE IF NOT EXISTS test" # mysql -u 用戶名 -e "sql語句" # 因為在my.cnf中配置了密碼,所以不用寫密碼了 mysql -u root -e "${DATABASE_SQL}"
4.shell創(chuàng)建mysql表
# sql語句 TEST_SQL="CREATE TABLE IF NOT EXISTS test ( id varchar(20) NOT NULL, text varchar(20) NOT NULL) ENGINE=InnoDB" # mysql -u 用戶名 -D "數(shù)據(jù)庫名" -e "sql語句" mysql -u root -D "test" -e "${TEST_SQL}"
5.shell添加數(shù)據(jù)
# sql語句 INSERT_SQL="insert into test values ('123', 'test')" mysql -u root -D "test" -e "${INSERT_SQL}"
6.shell刪除數(shù)據(jù)
DELETE_SQL="delete from test where id='123'" mysql -u root -D "test" -e "${DELETE_SQL}"
7.shell修改數(shù)據(jù)
UPDATE_SQL="update test set text='你好' where id='123'" mysql -u root -D "test" -e "${UPDATE_SQL}"
8.shell查找數(shù)據(jù)
SELECT_SQL="select id, text from test where id='123'" mysql -u root -D "test" -e "${SELECT_SQL}"
9.shell修改數(shù)據(jù)庫密碼
# mysql5.7之前 SQL="update mysql set password=password("新密碼") where user='root'" # mysql5.7及以后 SQL="update mysql set authentication_string=password("新密碼") where user='root'" # flush privileges:刷新 mysql -u root -D "mysql" -e "${SQL};flush privileges"
到此這篇關于通過shell腳本對mysql的增刪改查及my.cnf的配置的文章就介紹到這了,更多相關shell腳本mysql增刪改查內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
編寫shell腳本實現(xiàn)tomcat定時重啟的方法
這篇文章主要介紹了編寫shell腳本實現(xiàn)tomcat定時重啟的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12