import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.Date;import org.junit.Test;public class BatchUpdateTest {String url = "jdbc:mysql://localhost:3306/test";String userName = "root";String password = "123456";String driverName = "com.mysql.jdbc.Driver";int num = 10000;String strSql = "insert into students(stuno,name,gender,birthdate,major,age) values(?,?,?,?,?,?)";@Testpublic void slowTest() {Connection con = null;PreparedStatement pstmt = null;ResultSet rs = null;SimpleDateFormat hmFromat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 格式化日期String driverName = "com.mysql.jdbc.Driver";try {Class.forName(driverName); // 加载MySql的驱动程序con = DriverManager.getConnection(url, userName, password);con.setAutoCommit(false);// 根据参数的插入数据pstmt = con.prepareStatement(strSql);for (int i = 0; i < num; i++) {pstmt.setString(1, "20150111");pstmt.setString(2, "周迅");pstmt.setString(3, "f");pstmt.setString(4, hmFromat.format(new Date()));pstmt.setString(5, "电气工程");pstmt.setInt(6, 18);pstmt.executeUpdate();}con.commit();} catch (SQLException sqlE) {sqlE.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (rs != null)try {rs.close();} catch (Exception e) {e.printStackTrace();}if (pstmt != null){try {pstmt.close();// 关闭语句*/} catch (Exception e) {e.printStackTrace();}}if (con != null) {try {con.close();// 关闭连接} catch (Exception e) {e.printStackTrace();}}System.out.println("slow test end");}}@Testpublic void batchTest() {Connection con = null;PreparedStatement pstmt = null;ResultSet rs = null;SimpleDateFormat hmFromat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 格式化日期String driverName = "com.mysql.jdbc.Driver";try {Class.forName(driverName); // 加载MySql的驱动程序con = DriverManager.getConnection(url, userName, password);con.setAutoCommit(false);pstmt = con.prepareStatement(strSql);for (int i = 0; i < num; i++) {pstmt.setString(1, "20150111");pstmt.setString(2, "周迅");pstmt.setString(3, "f");pstmt.setString(4, hmFromat.format(new Date()));pstmt.setString(5, "电气工程");pstmt.setInt(6, 18);pstmt.addBatch();}pstmt.executeBatch();con.commit();} catch (SQLException sqlE) {sqlE.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (rs != null)try {rs.close();} catch (Exception e) {e.printStackTrace();}if (pstmt != null)try {pstmt.close();// 关闭语句*/} catch (Exception e) {e.printStackTrace();}if (con != null) {try {con.close();// 关闭连接} catch (Exception e) {e.printStackTrace();}}System.out.println("batch test end");}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。