JDBC PrepareStatement对象执行批量处理实例
以下是使用PrepareStatement对象进行批处理的典型步骤顺序 -
- 使用占位符创建SQL语句。
- 使用
prepareStatement()方法创建PrepareStatement对象。 - 使用
setAutoCommit()将自动提交设置为false。 - 使用
addBatch()方法在创建的Statement对象上添加SQL语句到批处理中。 - 在创建的
Statement对象上使用executeBatch()方法执行所有SQL语句。 - 最后,使用
commit()方法提交所有更改。
此示例代码是基于前面章节中完成的环境和数据库设置编写的。
以下代码片段提供了使用PrepareStatement对象的批量更新示例,将下面代码保存到文件:BatchingWithPrepareStatement.java -
// Import required packages
// See more detail at http://www.yiibai.com/jdbc/
import java.sql.*;
public class BatchingWithPrepareStatement {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Create SQL statement
String SQL = "INSERT INTO Employees(id,first,last,age) " +
"VALUES(?, ?, ?, ?)";
// Create preparedStatemen
System.out.println("Creating statement...");
stmt = conn.prepareStatement(SQL);
// Set auto-commit to false
conn.setAutoCommit(false);
// First, let us select all the records and display them.
printRows( stmt );
// Set the variables
stmt.setInt( 1, 400 );
stmt.setString( 2, "Python" );
stmt.setString( 3, "Zhang" );
stmt.setInt( 4, 33 );
// Add it to the batch
stmt.addBatch();
// Set the variables
stmt.setInt( 1, 401 );
stmt.setString( 2, "C++" );
stmt.setString( 3, "Huang" );
stmt.setInt( 4, 31 );
// Add it to the batch
stmt.addBatch();
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
// Again, let us select all the records and display them.
printRows( stmt );
// Clean-up environment
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
public static void printRows(Statement stmt) throws SQLException{
System.out.println("Displaying available rows...");
// Let us select all the records and display them.
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
System.out.println();
rs.close();
}//end printRows()
}//end JDBCExample
编译上面代码,如下 -
F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithPrepareStatement.java
执行上面代码如下所示 -
F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithPrepareStatement.java
F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs BatchingWithPrepareStatement
Connecting to database...
Thu Jun 01 04:46:38 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating statement...
Displaying available rows...
ID: 100, Age: 35, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
ID: 200, Age: 30, First: Curry, Last: Stephen
ID: 201, Age: 35, First: Kobe, Last: Bryant
Displaying available rows...
ID: 100, Age: 35, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
ID: 200, Age: 30, First: Curry, Last: Stephen
ID: 201, Age: 35, First: Kobe, Last: Bryant
ID: 400, Age: 33, First: Python, Last: Zhang
ID: 401, Age: 31, First: C++, Last: Huang
Goodbye!
F:\worksp\jdbc>
JDBC PrepareStatement对象执行批量处理实例的更多相关文章
- JDBC Statement对象执行批量处理实例
以下是使用Statement对象的批处理的典型步骤序列 - 使用createStatement()方法创建Statement对象. 使用setAutoCommit()将自动提交设置为false. 使用 ...
- PrepareStatement对象进行批处理的典型步骤顺序
https://www.yiibai.com/jdbc/preparestatement-batching-example.html 以下是使用PrepareStatement对象进行批处理的典型步骤 ...
- Java中反射机制和Class.forName、实例对象.class(属性)、实例对象getClass()的区别
一.Java的反射机制 每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图: 其中
- 用JDBC编程的执行时错误及其解决大全
用JDBC编程的执行时错误及其解决 用JDBC编程的执行时错误及其解决 源码: .java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlser ...
- 使用JDBC,完成数据库批量添加数据操作:
第一步:定义一个key String key = "into 表名(字段1,字段2,字段3)"; 第二步:定义一个可以增长的变量 StringBuffer values = new ...
- mybatis执行批量更新update
Mybatis的批量插入这里有http://ljhzzyx.blog.163.com/blog/static/38380312201353536375/.目前想批量更新,如果update的值是相同的话 ...
- 转:Filter的执行顺序与实例
转:http://www.cnblogs.com/Fskjb/archive/2010/03/27/1698448.html Filter的执行顺序与实例 Filter介绍 Filter可认为是Ser ...
- 使用Statement对象执行静态sql语句
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java ...
- 如何 ︰ 执行批量更新和插入使用.NET 提供程序在 C#.NET OpenXML
https://support.microsoft.com/zh-cn/kb/315968 如何 ︰ 执行批量更新和插入使用.NET 提供程序在 C#.NET OpenXML Email Prin ...
随机推荐
- kafka配置参数详解【收藏】
3.1 Broker Configs 基本配置如下: -broker.id -log.dirs -zookeeper.connect Topic-level配置以及其默认值将在下面讨论. ...
- Lintcode: Kth Largest Element 解题报告
Kth Largest Element Find K-th largest element in an array. Note You can swap elements in the array E ...
- DeepNLP的核心关键/NLP词的表示方法类型/NLP语言模型 /词的分布式表示/word embedding/word2vec
DeepNLP的核心关键/NLP语言模型 /word embedding/word2vec Indexing: 〇.序 一.DeepNLP的核心关键:语言表示(Representation) 二.NL ...
- 用Total Commander for Android管理应用程序
用Total Commander for Android管理应用程序 前不久安装了一个Total Commander的Anroid版本,除了用它来管理文件之外,我发现用它管理已安装程序挺不错的. 可以 ...
- [转]Oracle存储过程给变量赋值的方法
原文地址:http://blog.csdn.net/drbing/article/details/51821262 截止到目前我发现有三种方法可以在存储过程中给变量进行赋值:1.直接法 := ...
- 'Project Name' was compiled with optimization
'Project Name' was compiled with optimizationhtml, body {overflow-x: initial !important;}html { font ...
- [notes] some code tips
genericizing-codehtml, body {overflow-x: initial !important;}html { font-size: 14px; } body { margin ...
- 模式匹配的KMP算法详解
这种由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现的改进的模式匹配算法简称为KMP算法.大概学过信息学的都知道,是个比较难理解的算法,今天特把它搞个彻彻底底明明白白. 注意到这 ...
- Spring WebSocket初探2 (Spring WebSocket入门教程)<转>
See more: Spring WebSocket reference整个例子属于WiseMenuFrameWork的一部分,可以将整个项目Clone下来,如果朋友们有需求,我可以整理一个独立的de ...
- eclipse如何设置高亮代码的背景色,比如选中某个单词,高亮所有的
设置方法如下: 1.单击IDE顶部Window菜单下的Prefences,如图: 2.在打开对话框的左侧树上,找到Java节点下的Editor中的Mark Occurren,如图: 3.点击Mark ...