I have been reading a litle about the topic around the internet but i have found people that
says that you can't do it (so it is not possible) and other people that says you can do it with no problems,
for your information i have used the same statement for multiple queries, but i wonder if there's any problem
or issue with that.
It is not a problem if you want the same results. You can reuse queries saved to strings just like you can reuse any other variables. I would recommend you save your query to a string so that you can easily call it. I like to build the string at runtime. using varibles in the string to change the results of the query such as:
This builds a query that ends up looking somethign like this:
query = "UPDATE schema.table SET col1= 'John', col2 = 'Doe' WHERE col3 like 'Boston';";
Did I answer your question?
Joined: Dec 29, 2010
After rereading your question I feel like I missed the boat...
I use this method when querying databases with SELECT statements. I pass many different types in without any problems. If you wanted to change it to handle UPDATE/CREATE statement change statement.executeQuery(query); to statement.executeUpdate(query) and return something besides a ResultSet. Try and reuse code as much as possible. Hope this helps.
Joined: Nov 03, 2011
Hi, actually what i was trying to ask was about the class Statement in java.
I've used this class for multiple queries in the same class and it has worked.
But i was wonder if there's any issues with that.
I know what you mean by PreparedStatements the problem with that(at least what i know)
is that i would've to create more than a preparedstatement to do multiple queries. Because
a preparedstatement asks me for the sql and inmediatly compiles itself.
Of course you would have to use different ResultSets
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
You can do
In that loop, using a Statement is not efficient, because it's compiled again and again, which is a costly operation. Use PreparedStatement as advised above - it's more efficient.
Joined: Nov 03, 2011
Can you tell how would i use preparedstaments for this?
But using just one preparedstatement. Would it be the same?.
Also overall you can do some code improvements. Whenever using JDBC, ensure that Results, Statements and Connections are close()d in a finally block.
This ensures that all your JDBC resources are cleaned up even if there's an exception. The Resultset close()s are, strictly speaking, not necessary because statement.close would close them anyway; but it's good practice.>
subject: Are there any problems using the same statement for multiple queries?