简体   繁体   中英

Null Pointer Exception throws in getConnection()

I have the followiing situation: I have a java code which is connected with a database (MySQL). When i am running the java code from eclipse and taking data from database, everything is ok. But when i am running java code from html code as Applet, it throws Null Pointer Exception and i detect that problem in this case occur to the following java code:

private  Connection getConnection() throws SQLException{
   try {
        Class.forName("com.mysql.jdbc.Driver");
        String name="jdbc:mysql://localhost:3306/sensors_data";
        String username="root";
        String psw="11111";

        conn = DriverManager.getConnection(name,username,psw);
   } catch(Exception e) {
        e.printStackTrace();
   }
   return conn;

}

The object "conn" is null.

Well, if DriverManager.getConnection() throws an exception, you're printing out the exception but then returning conn anyway. You should probably be letting the exception propagate to the caller - after all, it's not like the caller now has a connection they can use.

(You're also catching any exception, instead of just SQLException , which is a bad idea.)

I wouldn't expect to be able to connect directly to a database from an applet though - I can't remember the exact restrictions on applet network connections, but that may well be the problem. Where is the database running compared with the web server? If it's not on the same host that the applet is published from, I wouldn't expect it to be able to make a connection at all without special permissions. (Trying to connect to localhost is particularly unlikely to work, I suspect.)

You should be able to see the exception thrown by DriverManager.getConnection in your debug log of course - that should be the first port of call, as well as fixing the exception handling.

将localhost替换为数据库所在的计算机名称,然后重试。

The problem is that you should return the conn inside the try{} thread. Or, you can create a connection variable as a class field, and then assign the conn value to the connection inside the try{} tread, then problem will be solved hopefully.

    public static Connection conn1 = null;

public static Connection getConnection(){
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection 
                ("jdbc:mysql://localhost/?user=root&password=root");
        if(conn != null){
            System.out.println("Connect database successfully.");
            conn1 = conn;
        }
        else System.out.println("Connection failed...");
        return conn;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM