日期:2014-05-16 浏览次数:20720 次
package com.gxa.edu; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JComboBox; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import java.awt.FlowLayout; import java.awt.Color; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author Administrator * 国信安百杰高端Java培训 */ public class Test extends JFrame { public final String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=stu"; public final String username = "sa"; public final String password = "123456"; public final String classdriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; public Connection conn; public Statement stmt; public ResultSet rs; public Test() { try { Class.forName(classdriver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 利用JDBC来创建表 */ public void createTable() { String sql = "create table batch (a1 varchar(10),a2 varchar(500))"; try { conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(); boolean f = stmt.execute(sql); System.out.println(f); } catch (SQLException e) { e.printStackTrace(); } } /** * 对数据库进行批量插入数据操作 * 执行次数100万 */ public void insertBatch() { //思路:将100万条数据分成n等份,1等份为1000条数据 //如何实现? //1、必须将Connection接口的自动提交方式改为手动 //2、利用Statement接口中的如下三个方法:addBatch、clearBath、executeBatch try { conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); stmt = conn.createStatement(); for (int i = 0; i < 1000000; i++) { String sql = "insert into batch values ('"+i+"', '第"+i+"条数据')"; //利用addBatch方法将SQL语句加入到stmt对象中 stmt.addBatch(sql); if (i % 1000 == 0 && i != 0) { //利用executeBatch方法执行1000条SQL语句 stmt.executeBatch(); stmt.clearBatch(); conn.commit(); } } stmt.executeBatch(); stmt.clearBatch(); conn.commit(); close(); //关闭资源 } catch (SQLException e) { e.printStackTrace(); } } public void close() { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Test t = new Test(); //t.createTable(); t.insertBatch(); } }