读取一个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