Home Database Mysql Tutorial 使用JDBC在MySQL数据库中快速批量插入数据_MySQL

使用JDBC在MySQL数据库中快速批量插入数据_MySQL

Jun 01, 2016 pm 01:18 PM
how interface database

bitsCN.com

使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(10W+),如何提高效率呢?

在JDBC编程接口中Statement 有两个方法特别值得注意:

void addBatch() throws SQLException
Copy after login
Adds a set of parameters to this PreparedStatement object's batch of commands.
int[] executeBatch() throws SQLException
Copy after login
Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. The int elements of the array that is returned are ordered to correspond to the commands in the batch, which are ordered according to the order in which they were added to the batch.
通过使用addBatch()和executeBatch()这一对方法可以实现批量处理数据。
不过值得注意的是,首先需要在数据库链接中设置手动提交,connection.setAutoCommit(false),然后在执行Statement之后执行connection.commit()。
package cyl.demo.ipsearcher;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class DbStoreHelper {	private String insert_sql;	private String charset;	private boolean debug;	private String connectStr;	private String username;	private String password;	public DbStoreHelper() {		connectStr = "jdbc:mysql://localhost:3306/db_ip";		// connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";		insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)";		charset = "gbk";		debug = true;		username = "root";		password = "***";	}	public void storeToDb(String srcFile) throws IOException {		BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), charset));		try {			doStore(bfr);		} catch (Exception e) {			e.printStackTrace();		} finally {			bfr.close();		}	}	private void doStore(BufferedReader bfr) throws ClassNotFoundException,	SQLException, IOException {		Class.forName("com.mysql.jdbc.Driver");		Connection conn = DriverManager.getConnection(connectStr, username,password);		conn.setAutoCommit(false); // 设置手动提交		int count = 0;		PreparedStatement psts = conn.prepareStatement(insert_sql);		String line = null;		while (null != (line = bfr.readLine())) {			String[] infos = line.split(";");			if (infos.length < 5)   continue;			if (debug) {				System.out.println(line);			}			psts.setLong(1, Long.valueOf(infos[0]));			psts.setLong(2, Long.valueOf(infos[1]));			psts.setString(3, infos[2]);			psts.setString(4, infos[3]);			psts.setString(5, infos[4]);			psts.addBatch();          // 加入批量处理			count++;					}		psts.executeBatch(); // 执行批量处理		conn.commit();  // 提交		System.out.println("All down : " + count);		conn.close();	}}
Copy after login

执行完成以后:
All down : 103498Convert finished.All spend time/s : 47
Copy after login
一共10W+,执行时间一共花费 47 秒.
这个效率仍然不高,似乎没有达到想要的效果,需要进一步改进。在MySQL JDBC连接字符串中还可以加入参数, rewriteBatchedStatements=true,mysql默认关闭了batch处理,通过此参数进行打开,这个参数可以重写向数据库提交的SQL语句,具体参见:http://www.cnblogs.com/chenjianjx/archive/2012/08/14/2637914.html useServerPrepStmts=false,如果不开启(useServerPrepStmts=false),使用com.mysql.jdbc.PreparedStatement进行本地SQL拼装,最后送到db上就是已经替换了?后的最终SQL.

在此稍加改进,连接字符串中加入下面语句(代码构造方法中去掉注释): connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";
再次执行如下:
All down : 103498Convert finished.All spend time/s : 10
Copy after login
同样的数据量,这次执行只花费了10秒 ,处理效率大大提高. bitsCN.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Inner class implementation of interfaces and abstract classes in Java Inner class implementation of interfaces and abstract classes in Java Apr 30, 2024 pm 02:03 PM

Java allows inner classes to be defined within interfaces and abstract classes, providing flexibility for code reuse and modularization. Inner classes in interfaces can implement specific functions, while inner classes in abstract classes can define general functions, and subclasses provide concrete implementations.

How does Go WebSocket integrate with databases? How does Go WebSocket integrate with databases? Jun 05, 2024 pm 03:18 PM

How to integrate GoWebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Store WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use the SELECT statement to retrieve messages from the database.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

See all articles