I'm pretty new to JDBC, so this is probably a very straightforward question.
I have to run several SQL statements, so I'm trying to write a generic "runSQLResultSet
" method that takes a String
sql statement and returns a ResultSet
. I want it to take care of opening the database connection, executing the statement, storing the ResultSet
in a CachedRowSetImpl
object (so that it will persist after the connection is closed), and closing the connection. I created a method that does this and it works.
My problem now is that I want to be able to use it for dynamic statements that are built with variables. I looked around, and it seems that I should really change my method to take a PreparedStatement
instead of just a plain String
. Then I can build the PreparedStatement
on the other side and pass it to the method. The problem is that I can't seem to create a PreparedStatement
without a Connection
object. I can open the connection before preparing the statement, but that defeats my purpose of factoring out the database processing into the runSQLResultSet
method. I need a way to build a SQL statement with dynamic components, without a connection object, and pass it to a method that will then execute it. Is there any way to do this with a PreparedStatement
? Is there any other statement object I can use instead? Otherwise - is there any better way to do this?