so I'm trying to connect to my database from java, I'm working in Eclipse, I watched a tutorial online and everything seemed to be working perfectly !!.. but when I wanted to connect another database on appache server.. the program starts running.. but nothing happens for a few minutes.. then I get the Null Pointer Exception message.. and at the line : st = con.createStatement(); this is the code:
package database_console;
import java.sql.*
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:80/mysql", "root", "admin");
st = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// to retrieve the results and print them out
public void getData(){
String query = "select DB from db";
try {
rs = st.executeQuery(query);
System.out.print("Records from Database");
while (rs.next()){
String DB = rs.getString("DB");
//String name = rs.getString("name");
//String password = rs.getString("password");
//int id = rs.getInt("id");
//System.out.print("ID: "+id+" Name: "+name+" password: "+password+"");
System.out.print("DB: " + DB );
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I later call the getData() function from another class where the main() is:
package database_console;
import java.io.IOException;
public class Main {
public static void main(String[] args){
DBConnect connect = new DBConnect();
connect.getData();
}
can u help me figure out what's wrong with my code? thanks.