# 登陆mysql:
mysql -uroot -proot
# 将数据导出到csv,关于为什么导出路径指定为/var/lib/mysql-files/,下文做解释
# csv格式参数介绍:
# fields terminated by ---- 字段终止字符
# optionally enclosed by ---- 封套符
# lines terminated by ---- 行终止符select * from aicmt into outfile '/var/lib/mysql-files/test.csv' fields terminated by',' optionally enclosed by'' lines terminated by'\n';
# 删除原表数据
deletefrom aicmt;
# 将csv中数据导入表中
load data local infile '/var/lib/mysql-files/test.csv'intotable aicmt fields terminated by',' lines terminated by'\n';
执行导出导入可能遇到的问题
报错:
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
解决1:
mysql -uroot-proot
show variables like '%secure%';
返回结果有:secure_file_priv=xxxxxx
导出的csv文件路径必须是secure_file_priv指定的路径
解决2:
修改MySQL安装路径下的my.cnf(vi /etc/my.cnf),在末尾添加“secure-file-priv=路径名”这一行,重启mysql(service mysqld restart)
将要通过load data infile的文件放在上面所定义的路径下进行操作即可
命令行操作mysql数据库
mysql -h172.30.1.46 -P3306 -uroot -proot -e “select * from aicmt” ecas;
shell脚本中操作mysql,并处理返回值
方法一:(执行sql,并获取返回值)
value=$(mysql -h172.30.1.46 -P3306 -uroot -proot -e"select count(1) from aicmt;" ecas);
或者
value=`mysql -h172.30.1.46 -P3306 -uroot -proot -e"select count(1) from aicmt;" ecas`;
# 对返回值进行加工# mysql -h172.30.1.46 -P3306 -uroot -proot -e "select count(1) from aicmt" ecas,执行结果返回两行,去第二行的第一个字段值
value=`mysql -h172.30.1.46 -P3306 -uroot -proot -e"select count(1) from aicmt" ecas|awk '{if (NR>1){print $1}}'`;
方法二:(执行sql,无法获取返回值)
#!/bin/bash
mysql -h172.30.1.46 -P3306 -uroot -hroot <<EOF
use ecas;
select * from aicmt;
EOF