0

i have an problem with my java program i'm trying to connect to an MYSQL database but it says driver not found i've imported mysql-connector-java into the project even with output set so it exports with the program

the class:

package com.CloudyProductions.GCDSS;

import java.sql.*;


public class mysql {

    public static  Connection c;

    static String host = "localhost";
    static String port = "3306";
    static String database = "";
    static String username = "root";
    static String password = "";

    public static void connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            c = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

I've added the mysql-connector to the project via maven and did what you said but now get this error:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    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.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
  • 2
    Then almost certainly your MySQL driver JAR is not on the classpath when you are running this program. Please tell us how you are running this code, from an IDE or from the command line. – Tim Biegeleisen Jan 30 '19 at 14:25
  • i export it and then run it via command prompt because i need it to run it on that way it's going to be an sort of server manager – Cloudy Productions Jan 30 '19 at 14:26
  • i won't work not gonna use it if it isn't working even tried setting up new program and there in maven still doesn't work – Cloudy Productions Jan 31 '19 at 15:02
  • If you use maven you read this also https://stackoverflow.com/questions/12811392/java-classnotfoundexception-with-maven-dependency – Petter Friberg Jan 31 '19 at 15:15

2 Answers2

0

You need to set your mysql driver jar into the classpath through command line as follows.

//for windows
set CLASSPATH=PATH_TO_JAR

//for unix
export CLASSPATH=PATH_TO_JAR

Or you can add it during execution of your application directly using -cp as,

java -cp PATH_TO_JAR your_class_app

or -classpath

java -classpath PATH_TO_JAR your_class_app
ScanQR
  • 3,740
  • 1
  • 13
  • 30
0

From this answer:

You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.

If you are using command line include the path to the driver jar using the -cp parameter of java.

For example:

java -cp C:\path\to\connector.jar Main
Hannes Schneidermayer
  • 4,729
  • 2
  • 28
  • 32