1、准备工作
查看数据库:
show databases;
切换数据库:
use 数据库名;
查看表名字
show tables;
2、单个表导出
需要替换导出csv文件目录和表名
sql
SELECT *
INTO OUTFILE '目录/文件名.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM 表名;
如果表太大,excel无法打开,可以显示导出的行数,例如10000行
sql
SELECT *
INTO OUTFILE '目录/文件名.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM 表名
LIMIT 10000;
3、导出全部表
当表太多的时候,可以使用下面的方法,一次性导出全部表;
需要替换数据库名。
sql
DELIMITER //
CREATE PROCEDURE ExportAllTablesToCSV()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tName VARCHAR(255);
DECLARE tCursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = '数据库名';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN tCursor;
read_loop: LOOP
FETCH tCursor INTO tName;
IF done THEN
LEAVE read_loop;
END IF;
SET @stmt = CONCAT('SELECT * FROM ', tName, ' INTO OUTFILE \'', tName, '.csv\' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\'');
PREPARE s1 FROM @stmt;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END LOOP;
CLOSE tCursor;
END //
DELIMITER ;
CALL ExportAllTablesToCSV();
4、修复
如果在导出时,报错:
Table '表名' is marked as crashed and should be repaired
检查表:
check table 表名;
修复表:
repair table 表名;