JDBC批量处理示例
2018-07-20 来源:open-open
如何使用JDBC进行批处理。
BatchExample.java:
package com.examples;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
public class BatchExample
{
public static void main(String[] args)
{
try (Connection connection = DBConnection.getConnection())
{
connection.setAutoCommit(false);
try (PreparedStatement pstmt = connection.prepareStatement("Insert into txn_tbl (txn_id,txn_amount, card_number, terminal_id) values (null,?,?,?)");)
{
pstmt.setString(1, "123.45");
pstmt.setLong(2, 2345678912365L);
pstmt.setLong(3, 1234567L);
pstmt.addBatch();
pstmt.setString(1, "456.00");
pstmt.setLong(2, 567512198454L);
pstmt.setLong(3, 1245455L);
pstmt.addBatch();
pstmt.setString(1, "7859.02");
pstmt.setLong(2, 659856423145L);
pstmt.setLong(3, 5464845L);
pstmt.addBatch();
int[] arr = pstmt.executeBatch();
System.out.println(Arrays.toString(arr));
connection.commit();
}
catch (SQLException e)
{
e.printStackTrace();
connection.rollback();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
DBConnection.java: package com.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
public static Connection getConnection() throws SQLException, ClassNotFoundException
{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jcg?rewriteBatchedStatements=true", "root", "toor");
return connection;
}
}
标签: Mysql
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:PHP从网络下载文件
下一篇:PHP生成随机密码
最新资讯
热门推荐