无报错但数据无法插入SQL数据库问题求助(附Java代码)
解决Java插入SQL数据无反应且无报错的问题
问题原因分析
- 循环逻辑无效:你通过
while(rs.next())遍历查询结果,只有当login_details表中已有数据时,循环才会执行。如果表是空的,这段代码直接跳过循环,插入语句根本不会运行。 - 条件判断错误:
if(status=false)是赋值操作(将false赋值给status),不是相等判断,正确写法应为if(status == false),且这段判断本身毫无意义——你初始将status设为false,完全不需要额外判断。 - 资源未释放:代码未关闭
Connection、Statement、ResultSet等资源,可能导致数据库连接泄漏。 - SQL注入风险:用
Statement拼接SQL语句,输入含特殊字符(如单引号)时会出错,还存在安全隐患。
修正后的代码
Connection conn = null; PreparedStatement pstmt = null; Scanner sc = new Scanner(System.in); try { // 获取用户输入 System.out.println("Enter Username"); String username = sc.next(); System.out.println("Enter Email"); String email = sc.next(); System.out.println("Enter Phone Number"); int phno = sc.nextInt(); System.out.println("Create a Password"); String password = sc.next(); // 建立数据库连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", "root", "abc"); // 使用PreparedStatement避免SQL注入,参数化查询更健壮 String insertQuery = "insert into login_details(user_name, user_email, user_phone, user_password) values(?, ?, ?, ?)"; pstmt = conn.prepareStatement(insertQuery); pstmt.setString(1, username); pstmt.setString(2, email); pstmt.setInt(3, phno); pstmt.setString(4, password); // 执行插入并判断结果 int affectedRows = pstmt.executeUpdate(); if (affectedRows > 0) { System.out.println("Details Entered Successfully"); } else { System.out.println("Failed to enter details"); } } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭资源,避免连接泄漏 try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); sc.close(); } catch (SQLException e) { e.printStackTrace(); } }
修正说明
- 移除了多余的查询和循环逻辑,直接执行插入操作(你的需求是插入数据,无需先查询表内容)。
- 用
PreparedStatement替代Statement,彻底避免SQL注入问题,同时让代码更稳定。 - 添加
finally块统一关闭资源,确保数据库连接被正确释放。 - 增加对
executeUpdate()返回值的判断,能明确知道插入是否成功。
内容的提问来源于stack exchange,提问作者Ninad Danane
相关产品推荐
相关产品推荐

