目录

简单的数据库造数据方法

目录

简单的数据库造数据方法

public class Snippet {
    public static void main(String[] args) {
        try {
               String url = "数据库URL"; 
               String user = "数据库用户名";
               String password = "数据库密码";
               StringBuffer sql = new StringBuffer();
               sql.append("insert into 表名(字段列) "
                    + "values (?,?,?)");
               Class.forName("oracle.jdbc.driver.OracleDriver");//oracle驱动
               Connection con = (Connection) DriverManager.getConnection(url,user,password);
               // 关闭事务自动提交
               con.setAutoCommit(false);
               final int batchSize = 10000;//每10000次提交一次
               int count = 0;
               Long startTime = System.currentTimeMillis();
               PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
               for (int i = 0; i < 100; i++) {
                pst.setString(1, "123");
                pst.setString(2, "2123");
                pst.setString(3, "14124123");
                // 把一个SQL命令加入命令列表
                pst.addBatch();
                if(++count % batchSize == 0 ){
                    pst.executeBatch();
                    count = 0;
                }
               }
               // 执行批量更新
               pst.executeBatch();
               // 语句执行完毕,提交本事务
               con.commit();
               Long endTime = System.currentTimeMillis();
               System.out.println("用时:" + (endTime - startTime));
               pst.close();
               con.close();
              } catch (ClassNotFoundException e) {
               e.printStackTrace();
              } catch (SQLException e) {
               e.printStackTrace();
              }
    }
}