views:

342

answers:

2
/**
 * 
 */
package ORM;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Gwilym
 * @version 0.0
 */
public class DatabaseConnection {

 private  String userName="";
 private  String password="";
 private  String host="";
 Connection conn;

/**
  * @param userName
  * @param password
  * @param host
  */
 public DatabaseConnection(String userName, String password, String host) {
  this.userName = userName;
  this.password = password;
  this.host = host;
 }

 public DatabaseConnection(String userName, String password, String host,boolean autoConnect) {
  this.userName = userName;
  this.password = password;
  this.host = host;
  if (autoConnect)
  {
  try {
   Connect();
  } catch (DatabaseConnectionException e) {
   e.printStackTrace();
  } 
  }
 }

/**
  * @return the connection
  */
 public Connection getConn() {
  return conn;
 }

 /**
  * @param userName the userName to set
  */
 public void setUserName(String userName) {
  this.userName = userName;
 }

 /**
  * @param password the password to set
  */
 public void setPassword(String password) {
  this.password = password;
 }

 /**
  * @param host the host to set
  */
 public void setHost(String host) {
  this.host = host;
 }

/**
 * Connect, attempts to connect to the MySQL database
 * with sun JDBC 
 * & MySQL driver
 * @param none
 * @return True iff connected;
 * @return False for all else;
 * @throws DatabaseConnectionException 
 */
public boolean Connect() throws DatabaseConnectionException
{
 // Attempt to load database driver
 try
    {
        String url = "jdbc:mysql:"+host;
        System.out.println(url);
        //Load driver
        Class.forName ("com.mysql.jdbc.Driver").newInstance ();

        conn = DriverManager.getConnection (url, userName, password);
    }
 catch (ClassNotFoundException cnfe) // driver not found
 {
  conn=null;
  System.err.println ("Unable to load database driver");
  throw new DatabaseConnectionException(cnfe);
 } 
 catch(InstantiationException ie)
 {
  conn=null;
  System.err.println ("Unable to Create database driver");
  throw new DatabaseConnectionException(ie); 
 }
 catch (IllegalAccessException iae)
 {
  conn=null;
  System.err.println ("Unable to Create database driver");
  throw new DatabaseConnectionException(iae);
 } catch (SQLException sqle) {
  conn=null;
  System.err.println ("SQL error");
  throw new DatabaseConnectionException(sqle);
 }

    if (conn!=null)
    {
        System.out.println ("Database connection established"); 
        return true;
    }
    else
    {
     System.out.println ("Database connection Failed"); 
        return false;
    }

}


/**
 * Disconnects the System from the mySQL database
 * 
 * @param none
 * @return true, if successful
 * @return false if not connection in existance 
 */
public boolean Disconnect()
{
 if (conn != null)
    {
        try
        {
            conn.close ();
            conn=null;
            System.out.println ("Database connection terminated normally");
            return true;
        }
        catch (Exception e) {
       //Ignore these errors as they all result in conn.close anyway
        }
        finally
        {
        conn=null;
        System.gc();
        // my removing the refrance to conncetion all calling the Garbage collecter we insure it is destoryed.
        }
        System.out.println ("Database connection terminated with errors");
        return true;    
    }
 else
 {
  System.out.println ("No Database connection present");
        return true;    
 }
}




}

The above code is called by

DatabaseConnection db =new DatabaseConnection("USERNAME","PASSWORD","//tel2.dur.ac.uk:3306/dcs8s07_SEG",true);

for obvious reasons I have removed the user name and password , but they can be aassumed to be correct.

Right down to the problem its self I get a com.mysql.jdbc.exceptions.jdbc4.CommunicationsException when ever this code is run with the details "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

My main problem at the moment is trying to discover what is actually going wrong.

In so far as I can tell the driver is being loaded correctly as my code does not throw a ClassNotFoundException, rather a SQLException of some kind.

So the problem is almost certainly the connection in some way. I can connect and query this database though a phpMyadmin located on the same server so I can assume that

1)The server is online 2)mySQL is working 3)the Username and password are correct 4) the database is present and i have the name correct

From this and "The driver has not received any packets from the server." I am wondering if the URL malformed?

URL= jdbc:mysql://tel2.dur.ac.uk:3306/dcs8s07_SEG

or there a simple setting that is incorrect on the server whihc is not allowing me to connect?

I have pondered on this problem and attempted several googles to no avail, so any idea would be of great help

thanks in advance SO!

+2  A: 

This is a wrapped exception. What's the root cause of this exception? Look further in the stacktrace.

A very common root cause is java.net.ConnectException: Connection refused. I've seen this in almost 99% of the cases. If this is true in your case as well, then all the possible causes are:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn't accept TCP/IP connections.
  6. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

To solve the one or the either, follow the following advices:

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start it.
  5. Verify if mysqld is started without the --skip-networking option.
  6. Disable firewall and/or configure firewall/proxy to allow/forward the port.

The username and password are irrelevant in this problem. At this point the DB can't even be reached. You would have gotten a "Login failed" or "Not authorized" SQLException otherwise.

BalusC
Hey BalausI have something very closeCaused by: java.net.ConnectException: Connection timed out: connect
Gwilym
Connection timed out usu. indicates that the firewall is blocking communication.
Andy Gherna
hey arghernawhich end do you think? my computer or the server?
Gwilym
just shh'd into a sever on the same network and pinged it so looks like its my firewall of all the bloody things
Gwilym
turned my firewall off still no joy sigh
Gwilym
`Connection timed out` is less or more the same. Follow the same advice.
BalusC
+1  A: 

In addition to the last post you should also do a low-level telnet test, this is the best way to verify connectivity. This test will tell you if there is a firewall or other software blocking access to that port.

telnet tel2.dur.ac.uk 3306

James
I get some some what intresting results I pinged it and gotC:\Users\Panda>ping tel2.dur.ac.ukPinging tel2.dur.ac.uk [129.234.200.251] with 32 bytes of data:Request timed out.Request timed out.Request timed out.Request timed out.Ping statistics for 129.234.200.251: Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),but I can still acess the phpMyadmin over http
Gwilym
the telnet tel2.dur.ac.uk 3306 command did't work when I popped it into cmd
Gwilym
Then it sounds like the port is blocked, do you have control over this host and the firewalls that surround it?
James
just shh'd into a sever on the same network and pinged it so looked like it was my firewall, but I turned off the windows which is the only on I have and still get the same exception
Gwilym
After you turned the firewall off, did the telnet connection work? If so load up mysql command line tool and try connecting with that. If that works then you know the problem is with your configuration and not with your network.
James
Hey Jamesthanks for all your helpAfter turning off my firewall I still cannot Ping or telnet from from my computer but can from the server I shh into, I am emailing the people in charge of the server to see if imn being block from that end.
Gwilym