java - null pointer exception on dao layer -


i have developed below program throwing null pointer exception.

below model class..

public class circle { private int id; public circle(int id, string name) { super(); id = id; this.name = name; } private string name; public int getid() { return id; } public void setid(int id) { id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } } 

below dao class..

public class jdbcdaoimpl { public circle getcircle(int circleid) { circle circle = null; try { class.forname("oracle.jdbc.driver.oracledriver"); connection con=drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:xe","saral","saral"); preparedstatement stmt=con.preparestatement("select * circle id = ?"); stmt.setint(1,circleid); resultset rset=stmt.executequery(); while(rset.next()) { circle= new circle(circleid, rset.getstring("name") ); } rset.close(); stmt.close(); con.close(); } catch (exception e) { e.printstacktrace(); } return circle; } } 

and main class..

public class jdbcdemo { public static void main(string[] args) { circle c = new jdbcdaoimpl().getcircle(1); system.out.println(c.getname()); } } 

please advise on execution of main class throwing null pointer exception.

you swallowing exceptions in dao method. returns null. return null if query returns empty result.

you fail close resources in finally. must propagate exceptions, not catch them without handling.

public class jdbcdaoimpl { public circle getcircle(int circleid) { connection con = null; try { class.forname("oracle.jdbc.driver.oracledriver"); con = drivermanager.getconnection( "jdbc:oracle:thin:@localhost:1521:xe","saral","saral"); final preparedstatement stmt = con.preparestatement( "select * circle id = ?"); stmt.setint(1,circleid); final resultset rset = stmt.executequery(); if (rset.next()) return new circle(circleid, rset.getstring("name") ); throw new runtimeexception("result set empty"); } catch (runtimeexception e) { throw e; } catch (exception e) { throw new runtimeexception(e); } { try { if (con != null) con.close(); } catch (throwable t) {} } } } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -