關於DBUtils中QueryRunner的基本用法
阿新 • • 發佈:2018-12-30
讀取一個Excel檔案裡面的內容,進行批量插入資料庫中;
一開始想的是,最基本的操作:遍歷一個一個的提交到資料庫裡面,這樣效率太低;
用了DBUtils中QueryRunner.batch()方法;
參考程式碼如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; public class Test { private static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; private static final String JDBC_URL = "jdbc:mysql://localhost:3306/taotao?characterEncoding=utf-8"; private static final String USER = "root"; private static final String PASSWORD = "123456"; public static void main(String[] args) { long a = System.currentTimeMillis(); int count = 1000; // 插入記錄的數目 Object[][] params = new Object[count][]; for (int i = 0; i < count; i++) // 將每條記錄的資料插入陣列 params[i] = new Object[] { (i+1)+"", "2", "3" }; batch(params); System.out.println(System.currentTimeMillis()-a); } public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER_CLASS_NAME); conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD); return conn; } catch (Exception e) { return null; } } public static void batch(Object[][] params) { QueryRunner queryRunner = new QueryRunner(true); String sql = "INSERT INTO TABLE_NAME VALUES (?,?,?)"; try { queryRunner.batch(getConnection(), sql, params); } catch (SQLException e) { e.printStackTrace(); } } }
參考連結:
https://www.cnblogs.com/wang-meng/p/5525389.html
https://blog.csdn.net/wang_shuyu/article/details/53232529