MySQL快速复制数据表数据方案

来源:互联网 发布:js文本框获得焦点 编辑:程序博客网 时间:2024/06/05 06:18

insert select ...... 语句组合方式效率低下,测试10000条数据大概需要14秒完成,可能测试不准确,但是效率低是一定的。

经过搜索找到如下方式,采用文件方式复制:


//登陆mysql

#mysql -h src_ip  -u root -p

mysql>use   xxx    //切换数据库

mysql>select * from table into outfile '/tmp/table.txt'   CHARACTER SET utf8; //生成数据文件 ,经过测试 这里使用的编码必须跟目标数据库的默认编码相同 如果目标数据库创建的时候默认字符集是utf8这里就写utf8,如果目标数据库创建的时候默认字符集是gbk就写gbk


然后登陆目标数据库(也可以是同一个数据库中不同表)

#mysql -h dest_ip  -u root -p    //登陆mysql

#mysql>use   xxx    //切换数据库

mysql>set names utf8;  //设置字符编码格式 ,经过测试,这一步是不需要的,load data的文件格式跟character_set_client、connection 、results无关,所以这一步可以不做。

mysql>load data local infile /tmp/table.txt'  into table 表名;

ps :into  outfile 生成的文件在  mysql-server上面,而不是client上。

该方案将insert select...语句开销转为文件IO开销,故而效率大大提高。



执行时报错:

Loading a local file in MySQL is a security hazard and is off by default, you want to leave it off if you can. When it is not permitted you get this error:

ERROR 1148 (42000): The used command is not allowed with this MySQL version

Solutions:

  1. Use --local-infile=1 argument on the mysql commandline:

    When you start MySQL on the terminal, include --local-infile=1 argument, Something like this:

    mysql --local-infile=1 -uroot -pmysql>LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE foo COLUMNS TERMINATED BY '\t';

    Then the command is permitted:

    Query OK, 3 rows affected (0.00 sec)Records: 3  Deleted: 0  Skipped: 0  Warnings: 0
  2. Or send the parameter into the mysql daemon:

    mysqld --local-infile=1
  3. Or set it in the my.cnf file (This is a security risk):

    Find your mysql my.cnf file and edit it as root.

    Add the local-infile line under the mysqld and mysql designators:

    [mysqld]local-infile [mysql]local-infile 


配置:

my.cnf 配置文件中加入


重新启动mysql后即可

0 0