• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

question on JDBC connection to MySQL

 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);

 
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic