我正在尝试更新汽车的价格,但我只能更新数据库中的一项。我认为我的逻辑是错误的。
有人可以建议我如何解决它。
MySQL 表:
+-----------+-----------+
| car | price |
+-----------+-----------+
| Bmw | 434312 |
| Audi | 222121 |
| Mercedes | 33333 |
+-----------+-----------+
HTML 代码:
<td><input TYPE="text" NAME="Bmw"></td>
<td><input TYPE="text" NAME="Audi"></td>
<td><input TYPE="text" NAME="Mercedes"></td>
Java 代码:
String Bmw=(String)session.getAttribute("Bmw");
session.setAttribute("Bmw",Bmw);
Bmw=request.getParameter("Bmw");
String Audi=(String)session.getAttribute("Audi");
session.setAttribute("Audi",Audi);
Audi=request.getParameter("Audi");
String Mercedes=(String)session.getAttribute("Mercedes");
session.setAttribute("Mercedes",Mercedes);
Mercedes=request.getParameter("Mercedes");
try {
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st = null;
session.setAttribute("st",st);
st = conn.createStatement();
String sqlqueryCommand = "select * from item";
ResultSet results = st.executeQuery(sqlqueryCommand);
while(results.next()) {
if(request.getParameter("Bmw")!=null && results.getString("car").equals("Bmw")) {
st.executeUpdate("update item set price='"+Bmw+"' where car='"+results.getString("car")+"'");
conn.commit();
}
if(request.getParameter("Audi")!=null && results.getString("car").equals("Audi")) {
st.executeUpdate("update item set price='"+Audi+"' where car='"+results.getString("car")+"'");
conn.commit();
}
if(request.getParameter("Mercedes")!=null && results.getString("car").equals("Mercedes")) {
st.executeUpdate("update item set price='"+Mercedes+"' where car='"+results.getString("car")+"'");
conn.commit();
}
}
conn.close();
}
catch(Exception e) {
System.out.println(e);
}