Java PreparedStatement 插入百万数据并比较主键和普通字段查询速度
这个异常是由于 PrepareStatement 的参数设置出错导致的。在使用 PrepareStatement 时,需要使用占位符来代替实际的参数值,然后通过 set 方法为占位符设置参数值。
下面是一个示例代码,展示如何正确使用 PrepareStatement 插入数据并比较查询速度差异:
import java.sql.*;
public class Main {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection('jdbc:mysql://localhost:3306/test', 'username', 'password');
// 插入 1000 万条数据
String sql = 'INSERT INTO your_table (column1, column2, ...) VALUES (?, ?, ...)';
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < 10000000; i++) {
// 设置参数值
pstmt.setInt(1, i);
pstmt.setString(2, 'value' + i);
// ...
pstmt.addBatch();
// 每 1000 条数据执行一次批量插入
if (i % 1000 == 0) {
pstmt.executeBatch();
pstmt.clearBatch();
}
}
// 根据主键查询一条数据
sql = 'SELECT * FROM your_table WHERE id = ?';
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
long startTime = System.currentTimeMillis();
rs = pstmt.executeQuery();
long endTime = System.currentTimeMillis();
System.out.println('根据主键查询耗时:' + (endTime - startTime) + 'ms');
// 根据普通字段查询一条数据
sql = 'SELECT * FROM your_table WHERE column1 = ?';
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
startTime = System.currentTimeMillis();
rs = pstmt.executeQuery();
endTime = System.currentTimeMillis();
System.out.println('根据普通字段查询耗时:' + (endTime - startTime) + 'ms');
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接和资源
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
在这个示例中,我们使用了占位符 '?' 来代替实际的参数值,并通过 set 方法为占位符设置参数值。然后使用 executeQuery 方法执行查询,并通过 System.currentTimeMillis() 方法记录起始时间和结束时间来计算查询耗时。
请根据你的表结构和具体需求修改示例代码中的表名、列名和连接信息。
原文地址: https://www.cveoy.top/t/topic/qnmU 著作权归作者所有。请勿转载和采集!