我在 eclipse jsp 文件中使用 mysql 更新时遇到问题。 我只是在我的 jsp 文件中使用 pstmt.executeUpdate。那是对的。 但是当我重新使用 pstmt.executeUpdate 来更新另一个主机的数据库时,我无法更新 mysql 数据。
当我在没有更新的“where”查询的情况下更新第二个 executeUpdate 时,它工作正常。我可以更新mysql数据。
但唯一的问题是,当我用“where”更新 executeUpdate 时,我无法更新 mysql 数据。
case1(没问题)
使用 preparedStatement1,用 'where' 更新查询 -> OK
使用 preparedStatement2,不带 'where' 更新查询 -> OK
案例2(问题)
使用 preparedStatement1,用 'where' 更新查询 -> OK
使用 preparedStatement2,使用 'where' 更新查询 -> 更新失败
(我已经在 mysql workbench 中测试了我的代码,第一次更新和第二次使用“where”进行更新都没有问题。我在 eclipse 中使用“where”代码添加更新时只有一个问题。)
后面是我的代码。
String DB_USER = (String)session.getAttribute("id");
String DB_PASSWORD = (String)session.getAttribute("password");
String DB_HOST = "jdbc:mysql://rds01.********.ap-northeast-2.rds.amazonaws.com:3306/inventory_" + DB_USER + "?useUnicode=true&characterEncoding=euckr";
Connection con;
PreparedStatement pstmt;
String query = "UPDATE inventory_"+DB_USER+" SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
pstmt.executeUpdate();
pstmt.close();
con.close();
String query_all = "UPDATE inventory_all SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
//behind host is another host with upper host.
DB_HOST = "jdbc:mysql://rds01.************.ap-northeast-2.rds.amazonaws.com:3306/inventory_all?useUnicode=true&characterEncoding=euckr";
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query_all);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
//------------upper code is OK, behind code is a problem ----------------
pstmt.executeUpdate();
pstmt.close();
con.close();
} catch(Exception e) {e.printStackTrace();}
最佳答案
对第二个查询使用不同的 PreparedStatement 对象。因为 一个
preparedstatement asks for the sql and immediatly compiles itself.
PreparedStatement pstmt1 = con.prepareStatement(sql1);
pstmt1.executeUpdate();
PreparedStatement pstmt2 = con.prepareStatement(sql2);
pstmt2.executeUpdate();
关于java - 当我在 eclipse jsp 文件中重用 pstmt.executeUpdate 时出现 mysql 更新错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34988324/