Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set query timeout on PreparedStatement?

Tags:

java

jdbc

Is there a way to get Connection.prepareStatement() to throw an error or return, instead of waiting for a row lock?

I am trying to implement cross-process synchronization with using a prepared statement, that i do not commit, so it grabs a write lock on a specific row. In the other processes it tries to prepare the sql statement, then it hangs while the original process finishes up. I need this to let me know it is hanging, so i can stop the function, and try again whenever it gets rescheduled.

Any ideas? Ive been googling for days, and can't seem to find a yes/no to this.

like image 245
Chris Avatar asked May 06 '11 15:05

Chris


People also ask

When should I close PreparedStatement?

Closing PreparedStatement Object A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.

Is PreparedStatement faster?

Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.

Can we use PreparedStatement for select query?

To retrieve data from a table using a SELECT statement with parameter markers, you use the PreparedStatement.

What does PreparedStatement setString do?

executeQuery(); Methods of PreparedStatement: setInt(int, int): This method can be used to set integer value at the given parameter index. setString(int, string): This method can be used to set string value at the given parameter index.


1 Answers

Im a fool, I figured this out yesterday and just forgot...

To solve it, do

preparedstatement = con.prepareStatement(query);
preparedstatement.setQueryTimeout(seconds);

and then just catch the exception.

like image 79
Chris Avatar answered Oct 05 '22 09:10

Chris