of {$slidecount} ½ {$title} ATZJG.NET {$author}

首页






MySQL 的备份与还原
Backup and restore


Haifeng Xu


(hfxu@yzu.edu.cn)

This slide is based on 刘增杰、张少军 《MySQL 5.5 从零开始学》

http://forums.mysql.com/

目录

数据备份

数据备份

使用 mysqldump

D:\tmp>mysqldump -uroot -p test_bar > test_bar.sql
Enter password: ******

D:\tmp>
-- MySQL dump 10.13  Distrib 5.6.17, for Win64 (x86_64)
--
-- Host: localhost    Database: test_bar
-- ------------------------------------------------------
-- Server version	5.6.17

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `bars`
--

DROP TABLE IF EXISTS `bars`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bars` (
  `name` varchar(20) NOT NULL,
  `addr` varchar(255) DEFAULT NULL,
  `license` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `bars`
--

LOCK TABLES `bars` WRITE;
/*!40000 ALTER TABLE `bars` DISABLE KEYS */;
INSERT INTO `bars` VALUES ('3DArtBar','上海虹梅路3338弄9-11号','BHXGZX'),('HardRock','上海政通路315号','XJ8QGF'),('Westside','上海衡山路237号','EDS9HF'),('宝莱纳餐厅','上海徐汇区汾阳路150号','SKAPXJ'),('木板房啤酒吧','上海子长路350号','YJVI9A'),('苏荷酒吧','扬州1912','LYMTD5'),('扬州老啤酒厂酒吧','广陵区南通东路128号','8NZBSG');
/*!40000 ALTER TABLE `bars` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `beers`
--

DROP TABLE IF EXISTS `beers`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `beers` (
  `name` varchar(20) DEFAULT NULL,
  `manf` varchar(50) DEFAULT NULL,
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `beers`
--

LOCK TABLES `beers` WRITE;
/*!40000 ALTER TABLE `beers` DISABLE KEYS */;
INSERT INTO `beers` VALUES ('百威','百威英博啤酒集团'),('贝克','百威英博啤酒集团'),('喜力','喜利得(中国)有限公司'),('嘉士伯','嘉士伯啤酒集团'),('安贝夫','英博啤酒集团下巴西安贝夫公司'),('南非啤酒','南非啤酒集团'),('米勒','SAB 公司'),('科罗娜','墨西哥摩洛哥啤酒公司'),('Stella Artois','百威英博啤酒集团'),('朝日','朝日啤酒株式会社'),('麒麟','麒麟(中国)投资有限公司'),('生力','香港生力啤酒廠有限公司'),('健力士黑啤','亚瑟健力士父子有限公司'),('纯种苦啤酒','马斯顿-汤普生-埃弗谢德公司');
/*!40000 ALTER TABLE `beers` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `drinkers`
--

DROP TABLE IF EXISTS `drinkers`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `drinkers` (
  `name` varchar(20) NOT NULL,
  `addr` varchar(255) DEFAULT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `drinkers`
--

LOCK TABLES `drinkers` WRITE;
/*!40000 ALTER TABLE `drinkers` DISABLE KEYS */;
/*!40000 ALTER TABLE `drinkers` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `frequents`
--

DROP TABLE IF EXISTS `frequents`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `frequents` (
  `drinker` char(20) NOT NULL DEFAULT '',
  `bar` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`drinker`,`bar`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `frequents`
--

LOCK TABLES `frequents` WRITE;
/*!40000 ALTER TABLE `frequents` DISABLE KEYS */;
/*!40000 ALTER TABLE `frequents` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `likes`
--

DROP TABLE IF EXISTS `likes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `likes` (
  `drinker` varchar(20) NOT NULL DEFAULT '',
  `beer` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`drinker`,`beer`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `likes`
--

LOCK TABLES `likes` WRITE;
/*!40000 ALTER TABLE `likes` DISABLE KEYS */;
/*!40000 ALTER TABLE `likes` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `sells`
--

DROP TABLE IF EXISTS `sells`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sells` (
  `bar` varchar(20) NOT NULL DEFAULT '',
  `beer` varchar(20) NOT NULL DEFAULT '',
  `price` double DEFAULT NULL,
  PRIMARY KEY (`bar`,`beer`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `sells`
--

LOCK TABLES `sells` WRITE;
/*!40000 ALTER TABLE `sells` DISABLE KEYS */;
INSERT INTO `sells` VALUES ('3DArtBar','安贝夫',40),('3DArtBar','百威',30),('3DArtBar','贝克',35),('3DArtBar','嘉士伯',32),('3DArtBar','喜力',25),('HardRock','安贝夫',39),('HardRock','百威',32),('HardRock','贝克',33),('HardRock','嘉士伯',30),('HardRock','健力士黑啤',39),('HardRock','科罗娜',40),('HardRock','喜力',28),('Westside','百威',32),('Westside','贝克',28),('Westside','朝日',26),('Westside','纯种苦啤酒',33),('Westside','健力士黑啤',39),('Westside','科罗娜',40),('Westside','南非啤酒',36),('宝莱纳餐厅','百威',32),('宝莱纳餐厅','朝日',26),('宝莱纳餐厅','纯种苦啤酒',33),('宝莱纳餐厅','健力士黑啤',39),('宝莱纳餐厅','科罗娜',40),('宝莱纳餐厅','南非啤酒',36),('宝莱纳餐厅','喜力',28),('木板房啤酒吧','安贝夫',40),('木板房啤酒吧','贝克',35),('木板房啤酒吧','嘉士伯',43),('木板房啤酒吧','米勒',32),('木板房啤酒吧','麒麟',30),('木板房啤酒吧','生力',25),('苏荷酒吧','百威',32),('苏荷酒吧','朝日',26),('苏荷酒吧','纯种苦啤酒',33),('苏荷酒吧','健力士黑啤',39),('苏荷酒吧','科罗娜',40),('苏荷酒吧','南非啤酒',36),('苏荷酒吧','生力',38),('苏荷酒吧','喜力',28),('扬州老啤酒厂酒吧','Stella Artois',36),('扬州老啤酒厂酒吧','安贝夫',40),('扬州老啤酒厂酒吧','百威',32),('扬州老啤酒厂酒吧','贝克',42),('扬州老啤酒厂酒吧','纯种苦啤酒',33),('扬州老啤酒厂酒吧','健力士黑啤',26),('扬州老啤酒厂酒吧','科罗娜',40),('扬州老啤酒厂酒吧','米勒',50),('扬州老啤酒厂酒吧','麒麟',39),('扬州老啤酒厂酒吧','喜力',35);
/*!40000 ALTER TABLE `sells` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2018-11-07 22:31:47

使用 phpMyAdmin

-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 2018-11-07 15:27:08
-- 服务器版本: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test_bar`
--

-- --------------------------------------------------------

--
-- 表的结构 `bars`
--

CREATE TABLE IF NOT EXISTS `bars` (
  `name` varchar(20) NOT NULL,
  `addr` varchar(255) DEFAULT NULL,
  `license` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

--
-- 转存表中的数据 `bars`
--

INSERT INTO `bars` (`name`, `addr`, `license`) VALUES
('3DArtBar', '上海虹梅路3338弄9-11号', 'BHXGZX'),
('HardRock', '上海政通路315号', 'XJ8QGF'),
('Westside', '上海衡山路237号', 'EDS9HF'),
('宝莱纳餐厅', '上海徐汇区汾阳路150号', 'SKAPXJ'),
('木板房啤酒吧', '上海子长路350号', 'YJVI9A'),
('苏荷酒吧', '扬州1912', 'LYMTD5'),
('扬州老啤酒厂酒吧', '广陵区南通东路128号', '8NZBSG');

-- --------------------------------------------------------

--
-- 表的结构 `beers`
--

CREATE TABLE IF NOT EXISTS `beers` (
  `name` varchar(20) DEFAULT NULL,
  `manf` varchar(50) DEFAULT NULL,
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

--
-- 转存表中的数据 `beers`
--

INSERT INTO `beers` (`name`, `manf`) VALUES
('百威', '百威英博啤酒集团'),
('贝克', '百威英博啤酒集团'),
('喜力', '喜利得(中国)有限公司'),
('嘉士伯', '嘉士伯啤酒集团'),
('安贝夫', '英博啤酒集团下巴西安贝夫公司'),
('南非啤酒', '南非啤酒集团'),
('米勒', 'SAB 公司'),
('科罗娜', '墨西哥摩洛哥啤酒公司'),
('Stella Artois', '百威英博啤酒集团'),
('朝日', '朝日啤酒株式会社'),
('麒麟', '麒麟(中国)投资有限公司'),
('生力', '香港生力啤酒廠有限公司'),
('健力士黑啤', '亚瑟健力士父子有限公司'),
('纯种苦啤酒', '马斯顿-汤普生-埃弗谢德公司');

-- --------------------------------------------------------

--
-- 表的结构 `drinkers`
--

CREATE TABLE IF NOT EXISTS `drinkers` (
  `name` varchar(20) NOT NULL,
  `addr` varchar(255) DEFAULT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- --------------------------------------------------------

--
-- 表的结构 `frequents`
--

CREATE TABLE IF NOT EXISTS `frequents` (
  `drinker` char(20) NOT NULL DEFAULT '',
  `bar` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`drinker`,`bar`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- --------------------------------------------------------

--
-- 表的结构 `likes`
--

CREATE TABLE IF NOT EXISTS `likes` (
  `drinker` varchar(20) NOT NULL DEFAULT '',
  `beer` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`drinker`,`beer`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- --------------------------------------------------------

--
-- 表的结构 `sells`
--

CREATE TABLE IF NOT EXISTS `sells` (
  `bar` varchar(20) NOT NULL DEFAULT '',
  `beer` varchar(20) NOT NULL DEFAULT '',
  `price` double DEFAULT NULL,
  PRIMARY KEY (`bar`,`beer`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

--
-- 转存表中的数据 `sells`
--

INSERT INTO `sells` (`bar`, `beer`, `price`) VALUES
('3DArtBar', '安贝夫', 40),
('3DArtBar', '百威', 30),
('3DArtBar', '贝克', 35),
('3DArtBar', '嘉士伯', 32),
('3DArtBar', '喜力', 25),
('HardRock', '安贝夫', 39),
('HardRock', '百威', 32),
('HardRock', '贝克', 33),
('HardRock', '嘉士伯', 30),
('HardRock', '健力士黑啤', 39),
('HardRock', '科罗娜', 40),
('HardRock', '喜力', 28),
('Westside', '百威', 32),
('Westside', '贝克', 28),
('Westside', '朝日', 26),
('Westside', '纯种苦啤酒', 33),
('Westside', '健力士黑啤', 39),
('Westside', '科罗娜', 40),
('Westside', '南非啤酒', 36),
('宝莱纳餐厅', '百威', 32),
('宝莱纳餐厅', '朝日', 26),
('宝莱纳餐厅', '纯种苦啤酒', 33),
('宝莱纳餐厅', '健力士黑啤', 39),
('宝莱纳餐厅', '科罗娜', 40),
('宝莱纳餐厅', '南非啤酒', 36),
('宝莱纳餐厅', '喜力', 28),
('木板房啤酒吧', '安贝夫', 40),
('木板房啤酒吧', '贝克', 35),
('木板房啤酒吧', '嘉士伯', 43),
('木板房啤酒吧', '米勒', 32),
('木板房啤酒吧', '麒麟', 30),
('木板房啤酒吧', '生力', 25),
('苏荷酒吧', '百威', 32),
('苏荷酒吧', '朝日', 26),
('苏荷酒吧', '纯种苦啤酒', 33),
('苏荷酒吧', '健力士黑啤', 39),
('苏荷酒吧', '科罗娜', 40),
('苏荷酒吧', '南非啤酒', 36),
('苏荷酒吧', '生力', 38),
('苏荷酒吧', '喜力', 28),
('扬州老啤酒厂酒吧', 'Stella Artois', 36),
('扬州老啤酒厂酒吧', '安贝夫', 40),
('扬州老啤酒厂酒吧', '百威', 32),
('扬州老啤酒厂酒吧', '贝克', 42),
('扬州老啤酒厂酒吧', '纯种苦啤酒', 33),
('扬州老啤酒厂酒吧', '健力士黑啤', 26),
('扬州老啤酒厂酒吧', '科罗娜', 40),
('扬州老啤酒厂酒吧', '米勒', 50),
('扬州老啤酒厂酒吧', '麒麟', 39),
('扬州老啤酒厂酒吧', '喜力', 35);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

数据库之间的迁移

相同版本的 MySQL 数据库之间的迁移

如果两个 MySQL 系统的主版本号相同, 则可以直接迁移. 迁移过程就是源数据备份和目标数据库还原.

# mysql --version
mysql  Ver 14.14 Distrib 5.5.54, for debian-linux-gnu (x86_64) using readline 6.2

Q. 将 www.atzjg.net 上的 MySQL 数据库全部迁移到 www.noooin.com 上, A. 在 www.atzjg.net 上执行下面的命令:

# mysqldump -h www.atzjg.net -uroot -pThePassword1 math | mysql -h www.noooin.com -uroot -pThePassword2

表的导出与导入

表的导出与导入

MySQL 数据库中的数据可以导出为 .sql 文本文件, .xml 文件或 .html 文件. 反过来, 这些文件(符合一定格式)也可以导入到 MySQL 数据库中.

用 SELECT ... INTO OUTFILE 'filename' 导出文本文件

导出的文件存储于服务器主机, 因此执行此命令的用户必须拥有 FILE 权限.

这里的 filename 不能是一个已经存在的文件.

语法

SELECT column_list FROM table_name WHERE condition
INTO OUTFILE 'filename' 
[OPTIONS]

这里 OPTIONS 可以不用写, 因为有默认值. 具体为:

FIELDS TERMINATED BY 'value'             -- default : '\t'
       [OPTIONALLY] ENCLOSED BY 'value'
	   ESCAPED BY 'value'                -- default : '\\'
LINES  STARTING BY 'value'               -- default : ''
       TERMINATED BY 'value'             -- default : '\n'

注意, 只能写一个 FIELDS, 一个 LINES. 如果都写, 那么 FIELDS 必须写在 LINES 前面.

实验

将 test_bar 数据库中的 bars 表备份到文件

mysql> use test_bar;
Database changed
mysql> show tables;
+--------------------+
| Tables_in_test_bar |
+--------------------+
| bars               |
| beers              |
| drinkers           |
| frequents          |
| likes              |
| sells              |
+--------------------+
6 rows in set (0.00 sec)

mysql> SELECT * FROM bars;
+------------------+-------------------------+---------+
| name             | addr                    | license |
+------------------+-------------------------+---------+
| 3DArtBar         | 上海虹梅路3338弄9-11号 | BHXGZX  |
| HardRock         | 上海政通路315号         | XJ8QGF  |
| Westside         | 上海衡山路237号         | EDS9HF  |
| 宝莱纳餐厅       | 上海徐汇区汾阳路150号   | SKAPXJ  |
| 木板房啤酒吧     | 上海子长路350号         | YJVI9A  |
| 苏荷酒吧         | 扬州1912                | LYMTD5  |
| 扬州老啤酒厂酒吧 | 广陵区南通东路128号     | 8NZBSG  |
+------------------+-------------------------+---------+
7 rows in set (0.00 sec)
mysql> SELECT name, addr, license FROM Bars
    -> WHERE addr LIKE "上海%"
    -> INTO OUTFILE "D:\\tmp\\test_bar-bars.txt"
    -> FIELDS TERMINATED BY ','
    ->        ENCLOSED BY '\"'
    ->        ESCAPED BY '\\'
    -> LINES STARTING BY '['
    ->       TERMINATED BY ']\r\n';
Query OK, 5 rows affected (0.04 sec)

检查 D:\tmp 目录下的文件

["3DArtBar","上海虹梅路3338弄9-11号","BHXGZX"]
["HardRock","上海政通路315号","XJ8QGF"]
["Westside","上海衡山路237号","EDS9HF"]
["宝莱纳餐厅","上海徐汇区汾阳路150号","SKAPXJ"]
["木板房啤酒吧","上海子长路350号","YJVI9A"]

与 LOAD DATA INFILE 的关系

SELECT ... INTO OUTFILELOAD DATA INFILE 是互补的, 后者可以将前者导出的数据导入到 MySQL 数据库中.

mysql> LOAD DATA LOCAL INFILE 'D:/tmp/test_bar-bars.txt'
    -> INTO TABLE Bars
    -> CHARACTER SET GBK
    -> FIELDS TERMINATED BY ','
    ->        OPTIONALLY ENCLOSED BY '"'
    ->        ESCAPED BY '\\'
    -> LINES  STARTING BY '[' 
	->        TERMINATED BY ']'
    -> ;

LOAD DATA INFILE 的语法

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
[REPLACE | IGNORE]
INTO TABLE tbl_name
[CHARACTER SET charset_name]
[{FIELDS | COLUMNS}
	[TERMINATED BY 'string']
	[[OPTIONALLY] ENCLOSED BY 'char']
	[ESCAPED BY 'char']
]
[LINES
	[STARTING BY 'string']
	[TERMINATED BY 'string']
]
[IGNORE number LINES]
[(col_name_or_user_var,...)]
[SET col_name = expr,...]

LOAD DATA INFILE 语句以非常快的速度从一个文本文件读取多行数据到一个数据表中.

注意, 使用LOAD DATA INFILE 语句时, 文件不能以 ucs2, utf16, utf32 字符集作为编码.

If you use LOW_PRIORITY, execution of the LOAD DATA statement is delayed until no other clients are reading from the table. This affects only storage engines that use only table-level locking (such as MyISAM, MEMORY, and MERGE). If you specify CONCURRENT with a MyISAM table that satisfies the condition for concurrent inserts (that is, it contains no free blocks in the middle), other threads can retrieve data from the table while LOAD DATA is executing. Using this option affects the performance of LOAD DATA a bit, even if no other thread is using the table at the same time.

如果使用 LOCAL 关键字, 则文件可以是客户机上的文件. 如果不指定 LOCAL, 则文件必须存在在服务器上.

表的导出与导入

表的导出与导入

用 mysqldump 命令导出文本文件

mysqldump 命令可以用来备份数据库, 也可以用来导出数据. 该工具不仅可以将数据导出为包含 CREATEINSERT.sql 文件, 也可以导出为纯文本文件.

语法

mysqldump -T path -u root -p db_name [tables] [OPTIONS]

这里的 OPTIONS

这里的 -T path 指导出数据存储的目录, 用于导出纯文本文件是才用此参数.

实验


使用 mysql 命令导入导出文本文件

使用 mysql 命令导入导出文本文件

用 mysql 命令导出文本文件

D:\tmp>mysql -uroot -p  --execute="SELECT * FROM Bars" test_bar > test_bar.txt
Enter password: ******

这个命令执行后即退出数据库.

使用 vim 查看得到的文件

D:\tmp>vim test_bar.txt
name    addr    license
3DArtBar        上海虹梅路3338弄9-11号 BHXGZX
HardRock        上海政通路315号 XJ8QGF
Westside        上海衡山路237号 EDS9HF
宝莱纳餐厅      上海徐汇区汾阳路150号   SKAPXJ
木板房啤酒吧    上海子长路350号 YJVI9A
苏荷酒吧        扬州1912        LYMTD5
扬州老啤酒厂酒吧        广陵区南通东路128号     8NZBSG

如果使用了单引号, 则导出的内容是 mysql 命令的使用方法.

D:\tmp>mysql -uroot -p  --execute='SELECT * FROM Beers' test_bar > test_bar-
beers.txt
mysql  Ver 14.14 Distrib 5.6.17, for Win64 (x86_64)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output 
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --bind-address=name IP address to bind to.
  --character-sets-dir=name 
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       Check memory and open file usage at exit.
  -T, --debug-info    Print some debug info at exit.
  -D, --database=name Database to use.
  --default-character-set=name 
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  --enable-cleartext-plugin 
                      Enable/disable the clear text authentication plugin.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  -G, --named-commands 
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers 
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names 
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -W, --pipe          Use named pipes to connect to server.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  --shared-memory-base-name=name 
                      Base name of shared memory.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert 
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=# 
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=# 
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
                      (Defaults to on; use --skip-secure-auth to disable.)
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --histignore=name   A colon-separated list of patterns to keep statements
                      from getting logged into mysql history.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.
  --connect-expired-password 
                      Notify the server that this client is prepared to handle
                      expired password sandbox mode.

Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\wamp\bin\mysql\mysql5.6.17\my.ini C:\wamp\bin\mysql\mysql5.6.17\my.cnf 
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
auto-rehash                       FALSE
auto-vertical-output              FALSE
bind-address                      (No default value)
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
database                          (No default value)
default-character-set             auto
delimiter                         ;
enable-cleartext-plugin           FALSE
vertical                          FALSE
force                             FALSE
named-commands                    FALSE
ignore-spaces                     FALSE
init-command                      (No default value)
local-infile                      FALSE
no-beep                           FALSE
host                              (No default value)
html                              FALSE
xml                               FALSE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              3306
prompt                            mysql> 
quick                             FALSE
raw                               FALSE
reconnect                         FALSE
shared-memory-base-name           (No default value)
socket                            /tmp/mysql.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
table                             FALSE
user                              root
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect-timeout                   0
max-allowed-packet                16777216
net-buffer-length                 16384
select-limit                      1000
max-join-size                     1000000
secure-auth                       TRUE
show-warnings                     FALSE
plugin-dir                        (No default value)
default-auth                      (No default value)
histignore                        (No default value)
binary-mode                       FALSE
connect-expired-password          FALSE

mysqlimport

mysqlimport

使用 mysqlimport 命令导入文本文件

mysqlimport 命令提供了与 LOAD DATA INFILE 语句相同的功能, 大多数直接对应 LOAD DATA INFILE 子句.

语法

mysqlimport -uroot -p db_name filename.txt [OPTIONS]

mysqlimport 命令的帮助文档

mysqlimport  Ver 3.7 Distrib 5.6.17, for Win64 (x86_64)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Loads tables from text files in various formats.  The base name of the
text file must be the name of the table that should be used.
If one uses sockets to connect to the MySQL server, the server will open and
read the text file directly. In other cases the client will open the text
file. The SQL command 'LOAD DATA INFILE' is used to import the rows.

Usage: mysqlimport [OPTIONS] database textfile...
Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\wamp\bin\mysql\mysql5.6.17\my.ini C:\wamp\bin\mysql\mysql5.6.17\my.cnf 
The following groups are read: mysqlimport client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.
  --bind-address=name IP address to bind to.
  --character-sets-dir=name 
                      Directory for character set files.
  --default-character-set=name 
                      Set the default character set.
  -c, --columns=name  Use only these columns to import the data to. Give the
                      column names in a comma separated list. This is same as
                      giving columns to LOAD DATA INFILE.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=name]  Output debug log. Often this is 'd:t:o,filename'.
  --debug-check       Check memory and open file usage at exit.
  --debug-info        Print some debug info at exit.
  --default-auth=name Default authentication client-side plugin to use.
  -d, --delete        First delete all rows from table.
  --fields-terminated-by=name 
                      Fields in the input file are terminated by the given
                      string.
  --fields-enclosed-by=name 
                      Fields in the import file are enclosed by the given
                      character.
  --fields-optionally-enclosed-by=name 
                      Fields in the input file are optionally enclosed by the
                      given character.
  --fields-escaped-by=name 
                      Fields in the input file are escaped by the given
                      character.
  -f, --force         Continue even if we get an SQL error.
  -?, --help          Displays this help and exits.
  -h, --host=name     Connect to host.
  -i, --ignore        If duplicate unique key was found, keep old row.
  --ignore-lines=#    Ignore first n lines of data infile.
  --lines-terminated-by=name 
                      Lines in the input file are terminated by the given
                      string.
  -L, --local         Read all files through the client.
  -l, --lock-tables   Lock all tables for write (this disables threads).
  --low-priority      Use LOW_PRIORITY when updating the table.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -W, --pipe          Use named pipes to connect to server.
  --plugin-dir=name   Directory for client-side plugins.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -r, --replace       If duplicate unique key was found, replace old row.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
                      (Defaults to on; use --skip-secure-auth to disable.)
  --shared-memory-base-name=name 
                      Base name of shared memory.
  -s, --silent        Be more silent.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert 
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  --use-threads=#     Load files in parallel. The argument is the number of
                      threads to use for loading data.
  -u, --user=name     User for login if not current user.
  -v, --verbose       Print info about the various stages.
  -V, --version       Output version information and exit.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
bind-address                      (No default value)
character-sets-dir                (No default value)
default-character-set             auto
columns                           (No default value)
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
default-auth                      (No default value)
delete                            FALSE
fields-terminated-by              (No default value)
fields-enclosed-by                (No default value)
fields-optionally-enclosed-by     (No default value)
fields-escaped-by                 (No default value)
force                             FALSE
host                              (No default value)
ignore                            FALSE
ignore-lines                      0
lines-terminated-by               (No default value)
local                             FALSE
lock-tables                       FALSE
low-priority                      FALSE
plugin-dir                        (No default value)
port                              3306
replace                           FALSE
secure-auth                       TRUE
shared-memory-base-name           (No default value)
silent                            FALSE
socket                            /tmp/mysql.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
use-threads                       0
user                              (No default value)
verbose                           FALSE

实验

C:\Users\haife>mysqlimport --print-defaults
mysqlimport would have been started with the following arguments:
--port=3306 --socket=/tmp/mysql.sock

End






Thanks very much!