通过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=SC2006STRING=`grep 'temporary password' /var/log/mysqld.log`PASSWORD=${STRING#*localhost: }
若已经修改了密码的
#!/bin/bash# shellcheck disable=SC2006PASSWORD='你的密码'
2.修改my.cnf文件
原因:在mysq5.6还是5.7以上,使用如下的shell脚本进行连接,会提示在命令行输入密码不安全。
mysql -u root -pPASSWORD -e 'xxxxxx'
解决方法:使用sed命令在my.cnf文件中添加如下字段
[client]user=rootpassword=xxxxxx
shell脚本:
# 我的my.cnf文件在/etc/my.cnf下,不相同的可以自己去找找# sed -i ’第几行 添加的内容’ 指定的文件sed -i ’1i [client]’ /etc/my.cnfsed -i ’2i user=root’ /etc/my.cnfsed -i ’3i password=xxxxxx’ /etc/my.cnf
3.shell创建mysql数据库
# SQL语句DATABASE_SQL='CREATE DATABASE IF NOT EXISTS test'# mysql -u 用户名 -e 'sql语句'# 因为在my.cnf中配置了密码,所以不用写密码了mysql -u root -e '${DATABASE_SQL}'
4.shell创建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 '数据库名' -e 'sql语句'mysql -u root -D 'test' -e '${TEST_SQL}'
5.shell添加数据
# sql语句INSERT_SQL='insert into test values (’123’, ’test’)'mysql -u root -D 'test' -e '${INSERT_SQL}'
6.shell删除数据
DELETE_SQL='delete from test where id=’123’'mysql -u root -D 'test' -e '${DELETE_SQL}'
7.shell修改数据
UPDATE_SQL='update test set text=’你好’ where id=’123’'mysql -u root -D 'test' -e '${UPDATE_SQL}'
8.shell查找数据
SELECT_SQL='select id, text from test where id=’123’'mysql -u root -D 'test' -e '${SELECT_SQL}'
9.shell修改数据库密码
# 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增删改查内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
