Search code examples
javamysqljarpackage

Connecting Java to MySQL - Package does not exist


I have spent many hours trying to figure this out and have followed many instruction but to no avail.

I am trying to connect my program up with my MySQL database, I have install the MySQL driver, or at least I think I have, I have added it to the class path, then I also installed it as a user library.

Then when I compile it through the command line I get an error: error: package com.mysql.jdbc does not exist

I even downloaded an earlier version of the driver jar and this did not work, I have spent probably a solid 8 hours trying to figure this out

My code:

String[] settings = new String[10];

    try {

        FileReader fr = new FileReader("settingsFile.txt");
        BufferedReader textReader = new BufferedReader(fr);

        for(int i=0; i <=9; i++){
                settings[i] = textReader.readLine();
            }

        textReader.close();

    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Unable to connect to database.\nSettings file Not Found");
    }

    String host = settings[2];
    String uName = settings[3];
    String uPass = settings[4];

    try {
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver).newInstance();
        Connection con = DriverManager.getConnection(host, uName, uPass);

        JOptionPane.showMessageDialog(null, "Connection to database established");
    }
    catch ( SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException err ) {
        JOptionPane.showMessageDialog(null, err.getMessage( ) + "\n\nDid not connect.");
    }

}

Please help, I think I am going grey over this.


Solution

  • You can only get this error if you have

    import com.mysql.jdbc.*;
    

    or one or more specific imports from that package.

    Solution: remove it. You don't need it. You should only be importing from java.sql.

    NB You haven't needed the Class.forName(driver).newInstance(); line since 2007.