0

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.

user3818372
  • 61
  • 1
  • 9

3 Answers3

1

I notice that you are trying to connect to port 80, i.e. "jdbc:mysql://localhost:80/mysql". That is very unusual for mysql. port 80 is the standard http port. The standard port for mysql is 3306. Pretty sure that is your problem.

skarist
  • 1,030
  • 7
  • 9
0

You must have exception in the console when creating the Connection object and that leads to Statement object is not initialized and which cause the NullPointException when you try to create ResultSet object from Statement object

The reason should be that you are using 80 as the port, while the default port is 3306 for MySQL. In this cause, you are not able to create the Connection object.

sendon1982
  • 9,982
  • 61
  • 44
0

Check your Connection details- hostUrl, username & password.

user153
  • 148
  • 1
  • 2
  • 10