1) Using try-with-resources Statements to Automatically Close JDBC Resources
We can use a try
-with-resources statement to automatically close java.sql.Connection
, java.sql.Statement
, and java.sql.ResultSet
objects. A try
-with-resources statement consists of a try
statement and one or more declared resources .We can separate the declared ressources by semicolons if there are multiple.
Let’s understand this with the following example. This example uses a try
-with-resources statement to close the Statement
object, stmt
, automatically:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static void viewTable(Connection con) throws SQLException { String query = "select FIRST_NAME,LAST_NAME,EMP_ID from EMPLOYEES"; <strong>try (Statement stmt = con.createStatement())</strong> { ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String firstName= rs.getString("FIRST_NAME"); String lastName= rs.getString("LAST_NAME"); String empID= rs.getString("EMP_ID"); } } } |
In the above example code , try
-with-resources statement that declares one resource, stmt.
When the try block terminates, the object stmt will be automatically closed.
2) Creating Row Sets with RowSetFactory Interface and RowSetProvider Class
JDBC 4.1 introduces a new interface called RowSetFactoryInterface and a new class called RowSetProvider class using which any types of row sets that are supported by the JDBC Driver can be created . The following example uses an instance of RowSetFactory
to create the JdbcRowSet
object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public void testJdbcRowSet(String username, String password) throws SQLException { RowSetFactory myRowSetFactory = null; JdbcRowSet jdbcRs = null; ResultSet rs = null; Statement stmt = null; try { myRowSetFactory = RowSetProvider.newFactory(); jdbcRs = myRowSetFactory.createJdbcRowSet(); jdbcRs.setUrl("jdbc:yourDriver:yourAttribute"); jdbcRs.setUsername(username); jdbcRs.setPassword(password); jdbcRs.setCommand("select FIRST_NAME,LAST_NAME,EMP_ID from EMPLOYEES"); jdbcRs.execute(); } catch(Exception e) { } |
The following statement creates the RowSetProvider
object myRowSetFactory
with the default RowSetFactory
implementation, com.sun.rowset.RowSetFactoryImpl
:
1 |
myRowSetFactory = RowSetProvider.newFactory(); |
Alternatively, if your JDBC driver has its own RowSetFactory
implementation, you can specify it as an argument of newFactory
.
The following statements create the JdbcRowSet
object jdbcRs
and configure its database connection properties:
1 2 3 4 5 |
jdbcRs = myRowSetFactory.createJdbcRowSet(); jdbcRs.setUrl("jdbc:myDriver:myAttribute"); jdbcRs.setUsername(username); jdbcRs.setPassword(password); |
The RowSetFactory
interface contains methods to create the different types of RowSet
implementations available in JDBC 4.1 and later:
createCachedRowSet
createFilteredRowSet
createJdbcRowSet
createJoinRowSet
createWebRowSet
Leave a Reply