JDBC COde in portlet

I wanted to try connecting to DB2 installed on my Windows box from my Linux box. So i built this simple portlet. The getJNDIConnection() method has sample of how to get connection from JDBC datasource. The getJDBCConnection() method has sample of how to make connection using simple JDBC connection(Dont use this in production)


private void queryDataBase(Connection con) throws Exception {
System.out.println("Entering queryDataBase()");
ResultSet rs = null;
try {
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM SUNPATIL.CONTACT");
while (rs.next()) {
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
con.close();
}
System.out.println("Exiting queryDataBase()");
}

private Connection getJNDIConnection() throws Exception {
System.out.println("Entering getJNDIConnection()");
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("/jdbc/localdb2");
System.out.println("After getting datasource " + ds);
Connection conn = ds.getConnection();
System.out.println("After getting Connection " + conn);
System.out.println("Exiting getJNDIConnection()");
return conn;
}

private Connection getJDBCConnection() throws Exception {
System.out.println("Entering getJDBCConnection()");
String url = "jdbc:db2://" + "192.168.174.1" + ":" + "50000" + "/"
+ "WIM";
System.out.println("JDBC URL is " + url);
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection conn = DriverManager.getConnection(url, "db2admin",
"db2admin");
System.out.println("After getting Connection " + conn);
System.out.println("Exiting getJDBCConnection()");
return conn;
}


You can download the sample portlet from here

No comments:

Post a Comment