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);
} c开发者_StackOverflow中文版atch(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.
Replace localhost with the machine name on which the database is located then try again.
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;
}
精彩评论