首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

MyEclipse JSP 連接 MySQL 讀取正常但寫入失效排查

     編輯:程式設計疑難解答

現象

登錄讀取數據正常,註冊寫入 `INSERT` 執行無異常但數據庫無數據。

代碼關鍵問題


String sql = "use jsgl;insert into jsgl.user values(...)";
// ...
Statement stmt = DB.createStmt(conn);
int n = DB.executeUpdate(stmt, sql);

原因分析

  1. SQL 語法錯誤:`use db; insert ...` 兩條語句需分別執行或用 `allowMultiQueries=true`。JDBC 默認單條執行,`use jsgl` 可能被忽略導致插入默認庫/無庫報錯但被吞掉。
  2. 表名錯誤:`insert into jsgl.user` 應為 `insert into user` (已 `use jsgl`),或去掉 `use jsgl` 直接 `insert into jsgl.user`。
  3. 事務未提交:若連接 `autoCommit=false`,需 `conn.commit()`。
  4. 異常吞噬:`DB.executeUpdate` 內部 `catch` 只打印堆疊不拋出,導致上層以為成功。

修正建議


// 1. 修正 SQL
String sql = "INSERT INTO user (name, account, pwd1, pwd2) VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, account);
ps.setString(3, pswd1);
ps.setString(4, pswd2);
int n = ps.executeUpdate();
// 2. 確保提交
conn.commit();
// 3. 捕獲異常上拋
} catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("註冊失敗", e);
}

最佳回答指正

`insert into jsgl.user` → `insert into user` (配合 `use jsgl`),或去掉 `use jsgl` 用全限定名。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved