When using JDBC in Java, the generally accepted method of querying a database is to acquire a connection, create a statement from that connection, and then execute a query from that statement.
// load driver
Connection con = DriverManager.getConnection(..);
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT..");
// ...
However, I am unsure of how to treat a second query to the same database.
-
Can another query be executed safely on the same
Statementobject, or must another statement be created from theConnectionobject in order to execute another query? -
If the same
Statementobject can be used for multiple queries, what is the purpose of theStatementclass (since it would then make more sense for aConnection.executeQuery()method to exist)?
Yes you can reuse the
Statementobject, but theResultSetobjects returned by theexecuteQuerycloses already opened resultsets.See the javadoc for the explanation
So the following occurs:
For example you can find an open source implementation of Statement in the jTDS project.
In the Statement.executeQuery() method you can see a call to
initialize()that closes all the resultsets already opened