0

I am trying to add a column to a database table and

PreparedStatement  ps = con.prepareStatement(query);  
ps.execute();
ps.close();

query is something like (valid SQL)

ALTER TABLE mytable ADD COLUMN mycolumn datatypeinfo

Anyway, it executes fine and the column is created. But the execute statement returns false. I tried with executeUpdate and that returns 0 rows.

Note that this whole thing is within a transaction with con.setAutoCommit set to false. So I am not sure if that is the problem. The issue is that I have to create the column before I can go ahead with other update queries. So it has to run in a transaction.

2
  • Why not use the executeUpdate() method when you don't expect a ResultSet? docs.oracle.com/javase/6/docs/api/java/sql/… Commented May 2, 2012 at 18:42
  • I tried that, but it doesn't return anything. As it says, it returns 0 for SQL statements that return nothing, such as DDL statement. I guess I will just rely on whether an exception has been thrown. Commented May 2, 2012 at 18:47

1 Answer 1

5

The return value of execute() does not indicate whether it was successful, but if the query that was run returned a result.

As the ALTER TABLE does not return a result, the execute() rightfully returns false

Quote from the Javadocs:

Returns: true if the first result is a ResultSet object; false if the first result is an update count or there is no result

Sign up to request clarification or add additional context in comments.

2 Comments

Fair enough, but how do I check if the column has been added? Do I need to use DatabaseMetaData to go back to the table and check if it is in effect? (In essence, can I do it in one step instead of two?)
If it fails, it will throw an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.