有时候我们需要将大量数据批量写入数据库,直接使用程序语言和Sql写入往往很耗时间,其中有一种方案就是使用MySqlLoaddatainfile导入文件的形式导入数据,这样可
add:
[mysqld]
local-infile=1
[mysql]
local-infile=1
客户端和服务端度需要开启,对于客户端也可以在执行命中加上--local-infile=1 参数:
mysql --local-infile=1 -uroot -pyourpwd yourdbname
如:
如:/usr/local/mysql/bin/mysql -uroot -h192.168.0.2 -proot databaseName --local-infile=1 -e "LOAD DATA LOCAL INFILE 'data.txt' into table test(name,sex) "
2, 编码格式注意:
若包含中文,请保证导入文件、连接字符串、导入表都是UTF-8编码。
3,执行
在使用LOAD DATA到MySQL的时候,有2种情况:
(1)在远程客户端(需要添加选项:--local-infile=1)导入远程客户端文本到MySQL,需指定LOCAL(默认就是ignore),加ignore选项会放弃数据,加replace选项会更新数据,都不会出现唯一性约束问题。
[zhuxu@xentest9-vm1 tmp]$mysql -uzhuxu -pzhuxu test -h10.254.5.151 --local-infile=1--show-warnings -v -v -v \
> -e "LOAD DATA LOCAL INFILE '/tmp/2.txt' INTO TABLE tmp_loaddata FIELDS TERMINATED BY ','";
(2)在本地服务器导入本地服务器文本到MySQL,不指定LOACL,出现唯一性约束冲突,会失败回滚,数据导入不进去,这个时候就需要加ignore或者replace来导入数据。
mysql>LOAD DATA INFILE '/home/zhuxu/1.txt' INTO TABLE tmp_loaddata FIELDS TERMINATED BY ',';
4,事务分析
步骤是这样的:
1,开启binlog,设置binlog_format=row,执行reset master;
2,load data infile xxxxx;
3,查看binlog。
可以看出,总共是一个事务,也通过mysqlbinlog查看了binary log,确认中间是被拆分成了多个insert形式。所以load data infile基本上是这样执行的:
begin
insert into values(),(),(),()...
insert into values(),(),(),()...
insert into values(),(),(),()...
...
...
commit
当然,由于row格式的binlog的语句并不是很明显的记录成多值insert语句,它的格式时
insert into table
set @1=
set @2=
...
set @n=
insert into table
set @1=
set @2=
...
set @n=
insert ...
;注意这里有一个分号‘;’,其实前面这一部分就相当于前面说的多值insert形式
然后接下来就重复上面的那种格式,也就是一个load data infile 拆成了多个多值insert语句。
前面说的是row格式记录的load data infile,那么对于statement是怎么样的呢?statement格式的binlog,它是这样记录的,binlog中还是同样的load data语句,但是在记录load data 语句之前,它会先将你master上这个load data 使用到的csv格式的文件拆分成多个部分,然后传到slave上(在mysql的tmpdir下),当然传这些csv格式的文件也会记录binlog event,然后最后真正的SQL语句形式就是load data local infile '/tmp/SQL_X_Y'这种形式(这里假设mysql的tmpdir是默认的/tmp),实际上这样很危险,比如tmpdir空间不够,那就会报错。不过从效率上来说两者可能差不多,因为statement格式的binlog也是拆分成了多个语句。
附:
(1)load data infile 和 load local data infile 在 innodb和MyISAM 同步方面的区别
对MyISAM引擎:
(1)对master服务器进行 ‘load’ 操作,
(2)在master上所操作的load.txt文件,会同步传输到slave上,并在tmp_dir 目录下生成 load.txt文件
master服务器插入了多少,就传给slave多少
(3)当master上的load操作完成后,传给slave的文件也结束时,
即:在slave上生成完整的 load.txt文件
此时,slave才开始从 load.txt 读取数据,并将数据插入到本地的表中
对innodb引擎:
(1)主数据库进行 ‘Load’ 操作
(2)主数据库操作完成后,才开始向slave传输 load.txt文件,
slave接受文件,,并在 tmp_dir 目录下生成 load.txt 文件
接受并生成完整的load.txt 后,才开始读取该文件,并将数据插入到本地表中
异常情况处理:
1)对MyISAM引擎
当数据库执行load,此时如果中断:
Slave端将报错,例如:
####################################################################
Query partially completed on the master (error on master: 1053) and was aborted.
There is a chance that your master is inconsistent at this point.
If you are sure that your master is ok,
run this query manually on the slave and then restart the slave with SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
START SLAVE; . Query: 'LOAD DATA INFILE '/tmp/SQL_LOAD-2-1-3.data' IGNORE INTO TABLE `test_1`
FIELDS TERMINATED BY ',' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (`id`, `name`, `address`)'
###########################################################################################
按照提示,在slave服务器上:
(1) 使用提示的load命令,将主服务器传输过来的load文件,在从服务器上执行
(2)让从服务器跳过错误。set global sql_slave_skip_counter=1;
(3)开启同步
2)对Innodb引擎
由于innodb是事务型的,所以会把load文件的整个操作当作一个事务来处理,
中途中断load操作,会导致回滚。
与此相关的一些参数:
max_binlog_cache_size----能够使用的最大cache内存大小。
当执行多语句事务时,max_binlog_cache_size如果不够大,
系统可能会报出“Multi-statement
transaction required more than 'max_binlog_cache_size' bytes of storage”的错误。
备注:以load data 来说,如果load的文件大小为512M,在执行load 的过程中,
所有产生的binlog会先写入binlog_cache_size,直到load data 的操作结束后,
最后,再由binlog_cache_size 写入二进制日志,如mysql-bin.0000008等。
所以此参数的大小必须大于所要load 的文件的大小,或者当前所要进行的事务操作的大小。
max_binlog_size------------Binlog最大值,一般设置为512M或1GB,但不能超过1GB。
该设置并不能严格控制Binlog的大小,尤其是Binlog遇到一根比较大事务时,
为了保证事务的完整性,不可能做切换日志的动作,只能将该事务的所有SQL都记录进
当前日志,直到事务结束
备注:有时能看到,binlog生成的大小,超过了设定的1G。这就是因为innodb某个事务的操作比较大,
不能做切换日志操作,就全部写入当前日志,直到事务结束。
(2)C# 批量插入Mysql
public void loadData(Connection connection)
{
long starTime = System.currentTimeMillis();
String sqlString = "load data local infile ? into table test";
PreparedStatement pstmt;
try {
pstmt = connection.prepareStatement(sqlString);
pstmt.setString(1, "tfacts_result");
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("program runs " + (endTime - starTime) + "ms");
}
public static void mysql_batch(string sqlStr,int point)
{
string sql = "insert into test(node1, node2, weight) values(?, ?, ?)";
Connection conn = getConn("mysql");
conn.setAutoCommit(false);
//clear(conn);
try
{
PreparedStatement prest = conn.prepareStatement(sql);
//long a = System.currentTimeMillis();
for (int x = 1; x
{
prest.setInt(1, x);
prest.setString(2, "张三");
prest.addBatch();
if (x % point == 0)
{
prest.executeBatch();
conn.commit();
}
}
prest.close();
//long b = System.currentTimeMillis();
//print("MySql批量插入10万条记录", a, b, point);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
close(conn);
}
引用:
本文出自 “小何贝贝的技术空间” 博客,请务必保留此出处

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.