Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic