0

My question is about the Update query shown in eclipse using MySQL, received from the code below

This is my database: enter image description here I'm trying to do on eclipse the next update query but I'm having trouble

 public static void update_Payment(String month,int number) {
    String sqlupdate = "UPDATE tenant SET month=?  WHERE appartmentnum =? ";

    try {
        PreparedStatement pst = connect.prepareStatement(sqlupdate);
        pst.setInt(1, 4);
        pst.setInt(2, 1);
        pst.executeUpdate();
    } catch (SQLException var2) {
        var2.printStackTrace();
    }

}

I know that I don't have column name month in my database, I just want to receive from the user the name of the month for example

this is working fine when I change [the column name from ] month to april or jan

thx for help

Jacob Barnes
  • 1,480
  • 1
  • 12
  • 29
Hai Vaknin
  • 37
  • 1
  • 8

1 Answers1

1

Since you are building this SQL statement as a string, please try the following:

 public static void update_Payment(String month,int number) {
    String sqlupdate = "UPDATE tenant SET " + month + "=? WHERE appartmentnum =? ";

    try {
        PreparedStatement pst = connect.prepareStatement(sqlupdate);
        pst.setInt(1, 4);
        pst.setInt(2, 1);
        pst.executeUpdate();
    } catch (SQLException var2) {
        var2.printStackTrace();
    }

}

You still have a problem:

You need a way to pass in the appropriate value for ?. There isn't a default way of converting month to month number. You can write a solution to that in code or db, e.g. Get month number from month name

Or of course just add another parameter and pass in the appropriate integer representing the month similar to what you're doing for apt#

Jacob Barnes
  • 1,480
  • 1
  • 12
  • 29