I have a table called colleagues and it has 6 columns: userid, firstname, lastname, title, squad, and email. The code I have typed for updating the first name is

String ID = textID.getText();
String first = textFirstName.getText();
String last = textLastName.getText();
String title = textTitle.getText();
String squad = textSquad.getText();
String email = textEmail.getText();

int newID = Integer.parseInt(ID);
int newSquad = Integer.parseInt(squad);

try {
    if(first != null) {
        String sql = "Update colleagues " + "set firstname = first " + "where userid = newID";
    JOptionPane.showMessageDialog(NewJFrame.this, "Updated");
} catch (SQLException err) {

The DoConnect(); after the if statement is just to update a jtable when I run the program.


You surely want to change this:

String sql = "Update colleagues " + "set firstname = first " + "where userid = newID"; 

You're writing first and newID as if they were the names of columns... when you want to actually add the actual values of your variables (with adequate escaping)

Check SQL Injection Prevention Cheat Sheet: MySQL Escaping

You're probably be better of with a prepared statement (you'll save yourself of the trouble of escaping, plus you'll have some extra documentation about the types of the parameters, plus you'll avoid risks of SQL injection):

if (first != null) {
    String sql = "UPDATE colleagues SET firstname = ? WHERE userid = ?";
    // Assuming there is a global variable for the connection, named con
    PreparedStatement upd = con.prepareStatement(sql);
    upd.setString(1, first); // replace first ? with value for first name
    upd.setInt(2, newID);    // replace second ? with value for userid
  • You're welcome. If you think this is a good answer to your question, it is customary to mark it as accepted, so that people can concentrate on answering other questions.
    – joanolo
    Jun 30 '17 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.