我目前正在研究java的更新声明。单击button
后,它将获取您放入textfield
的整数数据,它将从下拉列表中读取名称并提供相应的员工ID。数据库连接通过不同的类完成。
ActionListener myActionListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
DatabaseConnection connection = new DatabaseConnection();
if (connection.openConnection()) {
String ID = input1.getText();
int orderID = Integer.parseInt(ID);
String firstName = (String) cb.getSelectedItem();
System.out.println(firstName);
System.out.println(orderID);
if (firstName == "Patrick") {
int employeeId = 10;
String sql = "UPDATE barorder SET statusId=2, employeeId='" + employeeId + "' where id='" + orderID + "' ;";
}
}
}
};
这是我到目前为止所得到的,但我现在不知道如何执行SQL String。有什么建议吗?
答案 0 :(得分:3)
您可以使用PreparedStatement
更新查询,如下所示:
ActionListener myActionListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
DatabaseConnection connection = new DatabaseConnection();
PreparedStatement preparedStatement = null;
if (connection.openConnection())
{
String ID = input1.getText();
int orderID = Integer.parseInt(ID);
String firstName = (String) cb.getSelectedItem();
System.out.println(firstName);
System.out.println(orderID);
if (firstName == "Patrick")
{
int employeeId = 10;
String sql = "UPDATE barorder SET statusId=2, employeeId= ? where id= ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, employeeId);
preparedStatement.setInt(2, orderID);
preparedStatement.executeUpdate(sql);
}
}
}
};
答案 1 :(得分:0)
使用PreparedStatement
可以解决您的问题。
在我自己的项目中,我使用了这个
PreparedStatement prep = conn.prepareStatement("INSERT INTO Signup(Username, password, Email) VALUES(?, ?, ?)");
prep.setString(1, UserName);
prep.setString(2, Password);
prep.setString(3, Email);
prep.executeUpdate();
您可以从链接获得帮助:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html