Connect to a MySQL Database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    Connect to a MySQL Database

    Hi there,

    This thread is very similar to an earlier thread but I didn't want to hijack a thread.

    The issue is this. I have a mysql database on my local machine, I have installed the driver for Java and MySQL and using Eclipse I can connect to the database and see the tables etc.

    What I want to do is have a class that defines how to connect to a database and so I have been working on developing one. The code I have so far is:
    Code:
    package database.scratch;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    	public class DatabaseConnector {
    
    	
    	  public static void main(String args[]) {
    	    Connection con = null;
    
    	    try {
    	      Class.forName("com.mysql.jdbc.Driver").newInstance();
    	      con = DriverManager.getConnection("jdbc:mysql:///test",
    	        "root", "passowrd");
    
    	      if(!con.isClosed())
    	        System.out.println("Successfully connected to " +
    	          "MySQL server using TCP/IP...");
    
    	    } catch(Exception e) {
    	      System.err.println("Exception: " + e.getMessage());
    	    } finally {
    	      try {
    	        if(con != null)
    	          con.close();
    	      } catch(SQLException e) {}
    	    }
    	  }
    	}
    When I run this code the output in the console is:
    Code:
    Exception: com.mysql.jdbc.Driver
    There are apparently zero problems with the code in terms of compilation. Yet the Class.forName is throwing an exception.

    This really is the only output - it's certainly the only output I can see. If someone could point me in the right direction I would really appreciate it.

    Many thanks
    nathj
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    #2
    Here's a slight update to the code and the output:

    Code:
    public static void main(String args[]) {
    	    Connection con = null;
    
    	    try {
    	      Class.forName("com.mysql.jdbc.Driver").newInstance();
    	    }catch(Exception e1) {
    		      System.err.println("Exception: " + e1.getMessage());
    	    }
    	      try{
    	    	  con = DriverManager.getConnection("jdbc:mysql:///test", "root", "password");
    
    	      if(!con.isClosed())
    	        System.out.println("Successfully connected to " +
    	          "MySQL server using TCP/IP...");
    
    	    } catch(Exception e) {
    	      System.err.println("Exception: " + e.getMessage());
    	    } finally {
    	      try {
    	        if(con != null)
    	          con.close();
    	      } catch(SQLException e) {}
    	    }
    
    	  }
    The output:
    Code:
    Exception: com.mysql.jdbc.Driver
    Exception: No suitable driver found for jdbc:mysql:///test

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      1.) If you use e.printStackTra ce() you will get the full exception trace.
      2.) Is that class part of the project which you have installed the driver for?

      Comment

      • nathj
        Recognized Expert Contributor
        • May 2007
        • 937

        #4
        Thatnks for tip about printStackTrace . I used that as suggested (to both the catch sections e and e1) and I get the following output in the console:
        Code:
        Exception: com.mysql.jdbc.Driver
        java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        	at java.net.URLClassLoader$1.run(Unknown Source)
        	at java.security.AccessController.doPrivileged(Native Method)
        	at java.net.URLClassLoader.findClass(Unknown Source)
        	at java.lang.ClassLoader.loadClass(Unknown Source)
        	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        	at java.lang.ClassLoader.loadClass(Unknown Source)
        	at java.lang.ClassLoader.loadClassInternal(Unknown Source)
        	at java.lang.Class.forName0(Native Method)
        	at java.lang.Class.forName(Unknown Source)
        	at database.scratch.DatabaseConnector.main(DatabaseConnector.java:15)
        Exception: No suitable driver found for jdbc:mysql:///test
        java.sql.SQLException: No suitable driver found for jdbc:mysql:///test
        	at java.sql.DriverManager.getConnection(Unknown Source)
        	at java.sql.DriverManager.getConnection(Unknown Source)
        	at database.scratch.DatabaseConnector.main(DatabaseConnector.java:21)
        As a newbie to Java this doesn't mean a lot to me so any further help is greatly appreciated.
        nathj

        Comment

        • chaarmann
          Recognized Expert Contributor
          • Nov 2007
          • 785

          #5
          Have you downloaded the mysql-jdbc driver (called mySql Connector/J) from the mysql website and copied this .jar file to the described location on the tomcat server, where tomcat can find it? (lib-folder). If not, that's the problem.

          Comment

          • nathj
            Recognized Expert Contributor
            • May 2007
            • 937

            #6
            I believe so is the honest answer. Where should it be if I have done that? I'm really used to more straightforward set ups than that required by Java so I may have missed something or done it incorrectly.

            Cheers
            nathj

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #7
              You said earlier that you can connect using eclipse, does this mean that in this case you are now not using eclipse?
              In any case you need that jar to be on your classpath both when compiling the code and when running it.
              If you added the jar to the project's classpath using eclipse then you can run and compile in eclipse fine because eclipse will add it to the arguments to both javac and java.
              If you are running the javac and java commands yourself then you need to add the jar to the classpath yourself.

              Comment

              • nathj
                Recognized Expert Contributor
                • May 2007
                • 937

                #8
                Wow, this is getting clearer, a little bit at a time, thanks for your patience and continued help.

                I can connect in Eclipse using the Data Source Explorer. However, on running the code I get the output I posted above.

                The jar file is within the Java install on my local machine - I've checked that out and under the Data Source Explorer I can see that the class file is there under driver properties.

                If I look at the .classpath file in my project work space it is not mentioned. DO I need to add a reference to the driver there? If so what should I put in?

                Many thanks
                nathj

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by nathj
                  If I look at the .classpath file in my project work space it is not mentioned. DO I need to add a reference to the driver there? If so what should I put in?
                  The jar in which the driver class is stored is mentioned in the classpath; do the same when you want to run your stuff manually: mention the jar on the classpath in which the java driver is stored.

                  kind regards,

                  Jos

                  Comment

                  • chaarmann
                    Recognized Expert Contributor
                    • Nov 2007
                    • 785

                    #10
                    You can add the path to the driver-jar file directly to the classpath environment variable inside the shell where you run your java program from.
                    In windows, the best way is to add it to the system environment variables (so no need to set it manually in every cmd-box before you run the java-program, and it is available to all programs).
                    To do that, go to start --> settings --> control panel --> system --> advanced --> environment variables --> system variables --> new (or edit).
                    Variable name: CLASSPATH
                    Variable value: .;%JAVA_HOME%\l ib;C:\Program Files\Tomcat_4_ 1_12\common\lib ;

                    In my case, folder "C:\Program Files\Tomcat_4_ 1_12\common\lib " contains the file "mysql-connector-java-5.0.6-bin.jar",which is the downloaded JDBC-mySql-driver

                    Comment

                    • nathj
                      Recognized Expert Contributor
                      • May 2007
                      • 937

                      #11
                      chaarmann,

                      Thanks for the help, and thanks to everyone else who stopped by to help out. I now have it connecting beautifully. Bookmarking this thread for future reference though.

                      Cheers
                      Nathan

                      Comment

                      Working...