2

I am trying to connect to a database on a WAMP server on the same device the computer is running. Below is the code from a tutorial on zetcode. I have copied it almost completely except for the SQL login details. I am getting an error, it is displayed below the code.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.corba.se.impl.util.Version;

public class TestDb {

public static void main(String[] args) {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    String url = "jdbc:mysql://localhost:3306/mltest";
    String user = "mlcomponents";
    String password = "color12";
    try {
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT VERSION()");

        if (rs.next()) {
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
 }
}

Error message I am receiving:

May 25, 2016 3:51:28 PM TestDb main
SEVERE: No suitable driver found for jdbc:mysql://localhost:3306/mltest
java.sql.SQLException: No suitable driver found for   jdbc:mysql://localhost:3306/mltest
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at TestDb.main(TestDb.java:21)
bloopiebloopie
  • 309
  • 1
  • 4
  • 11

2 Answers2

1

I faced the same problem before, try to run this first:

Class.forName("com.mysql.jdbc.Driver");

This will make the driver to register itself.

Check for more information regarding the Drive Manager, MySQL Connector.

From previous link:

When you are using JDBC outside of an application server, the DriverManager class manages the establishment of connections. Specify to the DriverManager which JDBC drivers to try to make Connections with. The easiest way to do this is to use Class.forName() on the class that implements the java.sql.Driver interface.

Edit: I am adding a java class called MySQLConnector that can connect to mysql (in localhost) based on your second question. See how I import the java.sql.DriverManager

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

public class MySQLConnector {
    //JDBC driver name and database URL
    private String JDBC_DRIVER;  
    private String DB_URL;
    //Database credentials
    private String USER;
    private String PASS;
    private Connection conn;

    public MySQLConnector(){
        JDBC_DRIVER = "com.mysql.jdbc.Driver";
        DB_URL = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8";
        USER = "root";
        PASS = "123";
        conn = null;
    }
    public void openConnection(){
        try{
            //Register JDBC driver
            Class.forName(JDBC_DRIVER);         
            //Open a connection
            System.out.print("Connecting to a selected database... ");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Success!");     
        }catch(Exception e){
            //Handle errors for JDBC
            e.printStackTrace();
        }
    }
    public void closeConnection(){
        try{
            if(conn!=null)
            conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }
        System.out.println("Connection closed");
    }
    public Connection getConnection(){
        return conn;
    }
}
jsurf
  • 189
  • 3
  • 11
  • Hey I am now getting a class not found exception, I have put the .jar file from the zip folder from the website to the folder that the java class path points too and i am getting this exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver – bloopiebloopie May 26 '16 at 06:25
  • @bloopiebloopie Do you use an IDE like eclipse? The error occures on the import? I can't explain every case for ClassNotFoundException, please take a look here: http://stackoverflow.com/questions/17408769/how-do-i-resolve-this-java-class-not-found-exception I have updated my question so you can see a MySql connection. – jsurf May 26 '16 at 09:39
  • Hey I have only periodic access to the internet, I will test it now thanks. I do use eclips. – bloopiebloopie May 27 '16 at 13:40
  • @bloopiebloopie if you are still getting the same error, please check this [link](http://stackoverflow.com/questions/2353141/how-to-install-mysql-jdbc-driver-in-eclipse-web-project-without-java-lang-classn) it will save some time finding out what's wrong with the jar import/ClassNotFoundException – jsurf May 27 '16 at 14:09
  • Thanks for all your help those extra links worked a treat I have added the jar file correctly. I will try the rest of the code you have suggested now. Thanks very much again. – bloopiebloopie May 31 '16 at 11:06
  • @bloopiebloopie anytime! I pointed out the connector class to help you create an object that you can open close connection easily. – jsurf May 31 '16 at 11:08
  • Tried it there last night and it worked. Thanks again, for the education as much as the help. I rely appreciate it. – bloopiebloopie Jun 01 '16 at 14:19
1

First of all start Wamp on your pc, you dont need another class to make connection, use this code and provide the username and password of your wamp login, also this code is only for making a connection, add the above functionality yourself

public class Jdbcdemo {

    public static void main(String[] args) {
       try
       {
           //loading the jdbc driver
            Class.forName("com.mysql.jdbc.Driver").newInstance();
           //get a connection to database
           Connection myConn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctry","your username","your password");
           //create a statement
           Statement stmt=myConn.createStatement();
           //execute sql query
           ResultSet rs=stmt.executeQuery("select * from employee");
           //process the result
           while(rs.next())
           {
               System.out.println(rs.getString("name")+" = "+rs.getString(1));
           }          
       }
       catch(SQLException e)
       {
           System.out.println(e);   
       }
       catch(Exception e)
       {
           System.out.println(e);
       }
    }

}
vibhor vaish
  • 153
  • 1
  • 13
  • Hey vibhor vaish, The code worked perfectly. I had some issues with the connecting to the server and using the imported JAR file correctly other then that I got on grand. Thanks again for the code. – bloopiebloopie Jun 01 '16 at 14:21