“JDBC批量插入数据的操作”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第55行: | 第55行: | ||
} | } | ||
} | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 花费的时间为:19875 | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | |||
2023年1月3日 (二) 04:05的版本
https://www.bilibili.com/video/BV1eJ411c7rf/?p=32
建表
create table goods(
id int primary key auto_increment,
name varchar(25)
);
批量插入的方式1
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
for (int i = 1; i <= 20000; i++) {
String sql = "insert into goods(name) values('name_" + i + "')";
statement.execute(sql);
}
批量插入的方式2
//批量插入的方式二:使用 PreparedStatement
@Test
public void testInsert1() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
long start = System.currentTimeMillis();
connection = JDBCUtils.getConnection();
String sql = "insert into goods(name) values(?)";
preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
preparedStatement.setObject(1, "name_" + i);
preparedStatement.execute();
}
long end = System.currentTimeMillis();
System.out.printf("花费的时间为:%d\n", end - start);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.closeResource(connection, preparedStatement);
}
}
花费的时间为:19875
https://www.bilibili.com/video/BV1eJ411c7rf/?p=33