Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on JDBC connection to MySQL

 
rick collette
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I try to connect to my database, but it keeps giving me NullPointerException on "stmt". I am wondering what's wrong with my code? Thanks.

/*== database constants ==*/
String dbhost = "localhost";
String dbname = "mysql";
String dbuser = "***";
String dbpass = "***";
Connection db = null;
Statement stmt = null;
ResultSet rs = null;
String dbdriver = "org.gjt.mm.mysql.Driver";
/*== setup database driver and connect ==*/
try{
Class.forName(dbdriver).newInstance();
}catch (Exception ex){}
String conurl = "jdbc:mysql://localhost:3336 atabase01";
try{
db = DriverManager.getConnection(conurl, dbname, dbpass);
}catch (SQLException ex){}

/*== create sql query and execute ==*/
String sql = " SELECT id, name FROM sample ";
try {
stmt = db.createStatement();
rs = stmt.executeQuery(sql);
 
leo donahue
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rick,
In your code you set your Statement stmt = null;
Then you are trying to use that stmt variable which gives you your null pointer exception. Which I assume happens here:

Why not just: Statement stmt; // where you declare your constants
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hold on pardner!
Catching and burying Exceptions is not a good thing (except in the movies).
I'd bet that if you were to do a simple printStackTrace on your caught exceptions, you'd discover a problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic