IntelliJ中setModel绑定数据库数据失效,JDBC执行报错求助
问题排查与解决方案
错误核心原因
报错的本质是Statement与PreparedStatement的API混淆,加上变量重复定义导致的编译错误:
- 你先创建了
Statement实例,随后又将PreparedStatement实例赋值给同名的Statement变量,造成编译时类型不匹配。 java.sql.Statement的executeQuery()方法必须传入SQL字符串参数;而PreparedStatement的executeQuery()是无参的(SQL已在prepareStatement阶段传入)。代码中变量类型为Statement,但实际指向PreparedStatement实例,调用无参executeQuery()就会触发参数不匹配的编译错误。
修正后的代码
数据库操作代码
Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; void table_products(){ try{ // 获取数据库连接 conn = DriverManager.getConnection("jdbc:mysql://localhost/MyBakery?serverTimezone=UTC", "root", ""); // 使用PreparedStatement(推荐,防SQL注入) String sql = "SELECT * FROM products"; pstmt = conn.prepareStatement(sql); // PreparedStatement的executeQuery无需传参 rs = pstmt.executeQuery(); // 填充表格模型 table_products.setModel(DbUtils.resultSetToTableModel(rs)); }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(); } } }
额外注意事项
- 类型区分:严格区分
Statement和PreparedStatement,不要混用类型赋值。优先使用PreparedStatement,安全性更高。 - 资源释放:必须在
finally块中关闭ResultSet、PreparedStatement和Connection,防止数据库连接池耗尽。 - 驱动加载(可选):若遇到连接失败,可在获取连接前手动添加驱动加载代码:
Class.forName("com.mysql.cj.jdbc.Driver");(MySQL 8.0+版本可自动加载,但手动添加兼容性更好)。
内容的提问来源于stack exchange,提问作者Ray Paras
相关产品推荐
相关产品推荐

