Jessie Den Ridder Jessie Den Ridder - 5 months ago 17
SQL Question

Executing and sql String

I'm currently working on an update statement for java. After you click the

button
it will get the integer data you put into the
textfield
and it will read the name from the dropdown and give the corresponding employee ID. Database connection is done via a different class.

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 + "' ;";
}

}
}
};


This is what I got so far but I don't know how to execute the SQL String now. Any suggestions?

PVR PVR
Answer

You can use PreparedStatement to update query like this:

  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);

                }

            }
        }
    };
Comments