MySQL极速插入数据

mac2024-08-08  59

public class Main{ private static final String USER = "root"; private static final String PASSWORD = "root"; private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String DRIVER = "com.mysql.jdbc.Driver"; public static void main(String[] args) { long start = System.currentTimeMillis(); Connection connection = null; Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PASSWORD); // PreparedStatement StringBuilder sb = new StringBuilder("INSERT INTO student(sid, name, cid) VALUES"); String prefix = "student"; int i = 1; for (; i <= 100000; i++) { String sid = prefix + i; String cid = "class" + new Random().nextInt(10000) + 1; sb.append("(\"").append(sid).append("\", \"").append(sid).append("\", \"").append(cid).append("\")"); if (i < 100000) { sb.append(","); } } System.out.println(sb); long start1 = System.currentTimeMillis(); System.out.println("初始化sql耗时:" + (start1 - start) + "ms"); preparedStatement = connection.prepareStatement(sb.toString()); preparedStatement.addBatch(sb.toString()); preparedStatement.executeBatch(); System.out.println("执行sql耗时:" + (System.currentTimeMillis() - start1) + "ms"); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }

 

最新回复(0)