Null Pointer Exception throws in getConnection() - java

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.

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;
}

Related

Slow connection after connection to database with web-hosting

Heading ##I have problem with my java application with database in mySQL and swing GUI.
When I've used localhost everything worked properly. But now I would like to share project with my friend and we decided to use server hosting.
And here is a problem:
Now application works very slow, after pressing a button I have to wait a few seconds for the program to respond. Also the connection is lost from time to time. I have no idea where can I find reason for the problem... Do somebody now what is the reason of this problem?
private static Connection connection = null;
Boolean error = false;
private static String jdbcURL = "jdbc:mysql://host_name:3306/db_name";
private static String user = "user";
private static String password = "password";
MakeConnection(Connection connection) throws SQLException{
this.connection = connection;
try {
getConnection();
System.out.print("Connected to the data base in MakeConnection");
}
catch(Exception e) {
error = true;
System.out.print("Error in connection in MakeConnection consturctor" + e.getMessage());
}
finally{
if(connection!=null) connection.close();
if(error) System.out.print("Problem with connection");
else System.out.print("Program finished");
}
}
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Also sometimes application shows this error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I don't see any problem in your code. The problem is probably with your server hosting. You should check the country of the host provider and measure the time required to send a request to the server. Also you should use logger instead of System.out.println so you can examine required time for actions like db access, application logic and find a bottleneck.

why the JDBCs connection of service and dao are the same?

Just a simple demo of MVC.
In the Service class, there is a
JDBCutil db=new JDBCutil();
db.beginTransation();
UserinfoDao dao=new UserinfoDao();
In the UserinfoDao class, there is also a
JDBCutil db=new JDBCutil();
I thought there are two new JDBCutil, but there actually exists only one connection.
Why? Because of the db.beginTransation();? and why?
I am sorry that is my fault that not post the JDBCutil(thanks for the mention of comment), it maybe the "static connection"(looks like Singleton) one connection although two new .the code is
private static Connection conn=null;
private PreparedStatement pst;
//获取Connection连接
public Connection getConnection(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("加载Oracle驱动成功");
String url="jdbc:oracle:thin:#10.25.39.252:1521:orcl";
String userName="cccda";
String pwd="123456";
if(conn==null){
conn=DriverManager.getConnection(url, userName, pwd);
}
System.out.println("获取Connection连接成功");
} catch (ClassNotFoundException e) {
System.out.println("加载Oracle驱动失败");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("获取Connection连接失败");
e.printStackTrace();
}
return conn;
}
You are getting a new JDBCutil instance, but that's not an actual JDBC Connection. It might wrap a singleton connection with a per-user instance class. Without the code, we can't tell.
Also, since you see the word new twice, the JDBCutil instances are not the same, but again that doesn't mean they aren't both using the same JDBC Connection.
Odds are the db.beginTransaction() calls code internally that maps back to the same connection. If it didn't I'd imagine that you would have even bigger problems.

Best way to open and return a database connection in a Java application?

I have come up with the following utility class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySqlConnection
{
private static String dbUrl = "jdbc:mysql://localhost:3306/database";
private static String dbUsername = "root";
private static String dbPassword = "mysql";
public static Connection getConnection()
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (ClassNotFoundException e) {
System.out.println("Could not load JDBC driver: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Could not connect to DB: " + e.getMessage());
}
return connection;
}
}
The problem is: I do not want to return null from my method, because by doing so I force my callers to do a if (connection != null) {...} check every time they open and want to use a connection. I find these null checks to be error prone and want to avoid them at all costs. What other approach could I follow to manage database connections in my application?
First of all, as of JDBC 4.0 / Java 6, calling Class.forName() is no longer necessary. (See is Class.forName() necessary)
Next, don't bury the exceptions. Throw them up the stack, and let the callers decide how the exceptions should be handled. Depending on when getConnection() is being called you might want to:
Display an error popup box to the user
Try a different database for a connection
Run a script to try and check the status of the database and attempt to restart it if it appears to be down
Retry getConnection() completely
My point being, don't be afraid to throw Exceptions up the stack and let the caller handle the Exception appropriately.
All that being said, your getConnection() method should just need to store your DB URL, username, and password.
public class MySqlConnection
{
private static String dbUrl = "jdbc:mysql://localhost:3306/database";
private static String dbUsername = "root";
private static String dbPassword = "mysql";
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
}
}
Realistically, getConnection() will very very rarely throw an SQLException. The only scenario I've ever seen it throw an SQLException is because credentials were incorrect or the database was down.
You can throw an exception in your original code upwards, and then have to deal with a possible exception every time you would want to get a connection. Granted, you will not have null issues, but this could end up being more work. However, it does make it very explicit that you have to handle the connection not working, and this could be clearer than simply returning a null.
Refer these two questions , Should a retrieval method return 'null' or throw an exception when it can't produce the return value? and How to show if a method may return null
that should clear things a bit.
You can't avoid returning a NULL if you can't produce desired object ( In some cases, we have an option to return EMPTY objects but that is not applicable to JDBC connection object ) - All you can do is properly document your methods.
You should also avoid doing Sysouts and let the caller know about errors to expect by adding throws to your method and by re throwing exceptions. You have an option to wrap your exceptions to something more useful ( specific to your application ) before re throwing.
Also , do explicit NULL returns from your catch ( return NULL; ) instead of relying on last return statement - return connection; . There is no point of not returning immediately if not wiling to eat Exception and continue.
Lastly, you should try to use #Null and #NotNull annotations to properly document your methods.

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

In Java, how do I set a return type if an exception occurs?

hey all, I'm new to Java and was wondering if I define a method to return a database object
like
import java.sql.*;
public class DbConn {
public Connection getConn() {
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") == "development") {
String hostname = "localhost";
String username = "root";
String password = "root";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
return conn;
} catch(Exception e) {
throw new Exception(e.getMessage());
}
}
}
if the connection fails when I try to create it what should I return? eclipse is telling me I have to return a Connection object but if it fails I'm not sure what to do.
thanks!
UPDATED CODE TO LET EXCEPTION BUBBLE:
public class DbConn {
public Connection getConn() throws SQLException {
Connection conn;
String hostname = "localhost";
String username = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") != "development") {
hostname = "localhost";
username = "produser";
password = "prodpass";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
return conn;
}
}
If an exception is thrown, there is no normal value returned from the method. Usually the compiler is able to detect this, so it does not even pester you with "return required" style warnings/errors. Sometimes, when it is not able to do so, you need to give an "alibi" return statement, which will in fact never get executed.
Redefining your method like this
public Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") == "development") {
String hostname = "localhost";
String username = "root";
String password = "root";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
} catch(Exception e) {
// handle the exception in a meaningful way - do not just rethrow it!
}
return conn;
}
will satisfy Eclipse :-)
Update: As others have pointed out, re-throwing an exception in a catch block the way you did is not a good idea. The only situation when it is a decent solution is if you need to convert between different exception types. E.g. a method called throws an exception type which you can not or do not want to propagate upwards (e.g. because it belongs to a proprietary library or framework and you want to isolate the rest of your code from it).
Even then, the proper way to rethrow an exception is to pass the original exception into the new one's constructor (standard Java exceptions and most framework specific exceptions allow this). This way the stack trace and any other information within the original exception is retained. It is also a good idea to log the error before rethrowing. E.g.
public void doSomething() throws MyException {
try {
// code which may throw HibernateException
} catch (HibernateException e) {
logger.log("Caught HibernateException", e);
throw new MyException("Caught HibernateException", e);
}
}
You should just eliminate your entire try/catch block and allow exceptions to propagate, with an appropriate exception declaration. This will eliminate the error that Eclipse is reporting, plus right now your code is doing something very bad: by catching and re-throwing all exceptions, you're destroying the original stack trace and hiding other information contained in the original exception object.
Plus, what is the purpose of the line Class.forName("com.mysql.jdbc.Driver").newInstance();? You're creating a new mysql Driver object through reflection (why?) but you're not doing anything with it (why?).
Never, ever, ever use a generic exception like that. If you don't have a ready made exception (in this case, an SQLException), make your own exception type and throw it. Every time I encounter something that declares that it "throws Exception", and it turns out that it does so because something it calls declares "throws Exception", and so on down the line, I want to strangle the idiot who started that chain of declarations.
This is exactly the situation where you should let the exception propagate up the call stack (declaring the method as throws SQLException or wrapping it in a application-specific exception) so that you can catch and handle it at a higher level.
That's the whole point of exceptions: you can choose where to catch them.
I'm sorry, but you shouldn't be writing code like this, even if you're new to Java.
If you must write such a thing, I'd make it more like this:
public class DatabaseUtils
{
public static Connection getConnection(String driver, String url, String username, String password) throws SQLException
{
Class.forName(driver).newInstance();
return DriverManager.getConnection(url, username, password);
}
}
And you should also be aware that connection pools are the true way to go for anything other than a simple, single threaded application.
Try this one
public ActionForward Login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
MigForm migForm = (MigForm) form;// TODO Auto-generated method stub
Connection con = null;
Statement st = null;
ResultSet rs = null;
String uname=migForm.getUname();
String pwd=migForm.getPwd();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","uname","pwd");
if(con.isClosed())
{
return mapping.findForward("success");
}
//st=con.createStatement();
}catch(Exception err){
System.out.println(err.getMessage());
}
return mapping.findForward("failure");
}

Categories