user1024858
user1024858

Reputation: 129

Update statement in java

Hi all, This is my code,

public static boolean updateDB() {
  Connection cn = null; 
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  boolean result = false;   
  int number; 
  String insetSQL ="update quan set ten_quan='lin' where id=1"; 
  try {
    cn = LocalDatabasePooling.getInstance().getConnection();
    pstmt = cn.prepareStatement(insetSQL);
    pstmt.executeUpdate();
    result = true;
  } catch (SQLException e) {
    e.printStackTrace();
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException sqle) { }
    }
    if (pstmt != null) {
      try {
        pstmt.close();
      }
      catch (SQLException sqle) { }
    }
    if (cn1 != null) {
      try {
        cn1.close();
      }
      catch (SQLException sqle) { }
    }
  }
  return false;
}

Is the code above correct? But when I debug, I saw that the line

number = pstmt.executeUpdate();

was not executed and the code below it were not executed too.

when I add watch

pstmt.executeUpdate();

I saw this info

error(during the evaluation

What is wrong?

Upvotes: 0

Views: 284

Answers (3)

Gapton
Gapton

Reputation: 2134

You need to put ? in the statement, then insert the values into the preparedStatement.

If it is a simple "straight" SQL you want to execute, there is no need for using a PreparedStatement

Upvotes: 0

karthi keyan
karthi keyan

Reputation: 1

pstmt.executeUpdate(); not executed - That is OK. But what are you getting ? A exception trace in the command line ? Try to add try catch block as mentioned BalusC and run the problem again. There may be problem with your sql , like table not exist , column name is incorrect or your datasouce hasn't return the connection at all. you might get a null pointer exception.

Upvotes: 0

BalusC
BalusC

Reputation: 1108642

Apparently an exception was been thrown which was completely ignored by your code. Something like:

try {
    // Your code was here.
} catch (SQLException e) {
    // But you didn't put anything here.
}

You should at least log/print the stacktrace

try {
    // Your code was here.
} catch (SQLException e) {
    e.printStackTrace();
}

Or, even better, just throw it.

public SomeObject someMethod() throws SQLException {
    try {
        // Your code was here.
    } finally {
        // Surely close resources here.
    }
}

Exceptions contain a wealth of information about the cause of the problem and they should not be ignored, unless you really know what you're doing.

Upvotes: 2

Related Questions