Java JdbcRowSet Example
In this section we will see an example of JdbcRowSet.
javax.sql.rowset.JdbcRowSet is an interface that facilitate to wrap the ResultSet object.
Example
Here I am going to give a simple example which demonstrates how JdbcRowSet can be used. In this example I have created a class where I have used the JdbcRowSet interface and wrapped the ResultSet inside it. Before this I have created an emp database table using ms access and field some records into the respected fields. In the main method of this class loaded the driver for executing the sql codes and established a connection with the database using getConnection() method of DriverManager class. To established a connection with the database it is required to create a DSN so I have created DSN by the name swing using Control Panel -> Administrative Tool -> Data Sources -> System DSN-> Add-> Microsoft Access Driver (*.mdb) -> DSN Name -> Select Directory -> ok ->ok -> ok. Then write a SQL query for displaying all records of emp table then passed this SQL statement to the prepareStatement() method of Connection class and then executed this query using ps.executeQuery() which returns the ResultSet. Then instantiate the JdbcRowSet using the class JdbcRowSetImpl and passed the ResultSet object inside this class parameter which wraps the ResultSet object. Then traverse the records until the JdbcRowSet has the ResultSet object and then displayed these results after fetching them in their respective types. Before executing this example you will have to download the jar file for com.sun.rowset.JdbcRowSetImpl. Here I am giving the jar file of com.sun.rowset, you can download the jar files from here com.sun.rowset jar
Source Code
JavaJDBCRowSetExample.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.rowset.JdbcRowSet; import com.sun.rowset.JdbcRowSetImpl; public class JavaJDBCRowSetExample { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager. getConnection("jdbc:odbc:swing"); String sql = "select * from emp"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); JdbcRowSet jrs = new JdbcRowSetImpl(rs); System.out.println("Records of emp table"); System.out.println("id \t fName \t lName \t address"); while (jrs.next()) { int id = jrs.getInt("id"); String fName = jrs.getString("fName"); String lName = jrs.getString("lName"); String address = jrs.getString("address"); System.out.println(id+" \t "+fName+" \t "+lName +" \t "+address); } rs.close(); ps.close(); } catch(SQLException sex) { System.out.println(sex); } catch(Exception ex) { System.out.println(ex); } } }
Output
This example is created in Eclipse. When you will execute the above example you will get the output as follows :