导出,导入数据库mysqldump

使用mysql提供的mysqldump工具来导入导出数据库,可以实现数据库的备份和还原。

导出数据库 (备份数据库)
导出数据库:mysqldump -u 用户名 -p 数据库名 > 导出的文件名

导入数据库 (还原数据库)
导入数据库

导入前先模拟将要还原的数据库删除
导入数据库(还原数据库)
或者登陆 mysql 创建数据库

导入
进入到mysql数据库,添加sql文件,推荐使用此方法,安全
mysql> source /root/HA.sql #sql脚本的路径

扩展知识
上面导出数据库不能导出数据库结构,需要我们导入数据库时新建数据库,可以使用-B参数在导出数据库时,同时导出数据库结构,这样我们在导入数据库时不用先创建要导入的数据库的库结构。

Mysqldump -uroot -p123456 -B 库名>文件.sql
-B : 导出整个库包含建库语句
-A:导出全部数据库

把一个select的结果导出到文本
语法:
select * into outfile ‘/tmp/123.txt’ from HA.students; 此处有个文件访问权限问题,mysql用户是可以访问/tmp路径的,所以这里放到tmp下

举例:
查找HA数据库下students表的数据导出到/tmp目录下

mysql> select * into outfile ‘/tmp/123.txt’ from HA.students;
 ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

报错:

5.7版本导出报错,ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

是因为secure-file-priv 这个选项规定了导出的目录,查看导出目录。

mysql> show variables like ‘%secure%’;

mysql 导入到openGauss mysql 导入数据库_导入数据

secure_file_priv 为 NULL 时,表示限制mysqld不允许导入或导出。

secure_file_priv 为 /tmp 时,表示限制mysqld只能在/tmp目录中执行导入导出,其他目录不能执行。

secure_file_priv 没有值时,表示不限制mysqld在任意目录的导入导出。
解决方法

打开my.cnf在文件末尾加入以下语句后重启mysql。

[root@cong11 ~]# vim /etc/my.cnf
 secure_file_priv=’’

重启Mysql服务

[root@cong11 ~]# /etc/init.d/mysqld restart

查看修改结果

mysql> show variables like ‘%secure%’;

mysql 导入到openGauss mysql 导入数据库_mysql_02

重新执行
mysql> select * into outfile ‘/tmp/123.txt’ from HA.students;
Query OK, 9 rows affected (0.02 sec)

mysql-sql语句进阶

查看字段类型:
desc 表名

逻辑运算符:
and or not
and 与
or 或
not 非

算术运算符:
= 等于
<> 不等于 !=
“> 大于”
< 小于
“>= 大于等于”
“<= 小于等于”

in 运算符
IN 运算符用于 WHERE 表达式中,以列表项的形式支持多个选择,语法如下:
WHERE column IN (value1,value2,…)
WHERE column NOT IN (value1,value2,…)
Not in 与in相反
当 IN 前面加上 NOT 运算符时,表示与 IN 相反的意思,即不在这些列表项内选择。

排序
升序与降序
升序:order by “排序的字段” asc 默认
降序:oredr by “排序的字段” desc

范围运算:
between …and…
查找价格在30到60之间(包含30和60)的书名和价格
mysql> select bname,price from books where price between 30 and 60;

Between and 可以使用>=和<=的方式来代替,并且使用大于小于意义表述更明确。
mysql> select bname,price from books where price >=30 and price <=60;

查找价格不在30到60之间的书名和价格
模糊匹配查询:
字段名 [not]like ‘通配符’ ----》% 任意多个字符
查找书名中包括"程序"字样记录
mysql> select bName from books where bName like ‘%程序%’;
查找书名中不包括"程序"字样记录
mysql> select bName from books where bName not like ‘%程序%’;