Problem connecting mysql and Java

I am trying to connect Java code to mySQL. Here is the error I received. I do not understand why the driver was not found, since I installed the jar connector in the classpath.

Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
    at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
    at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
    at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
    at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
 upDomain(HSystemRDB.java:198)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
    at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)

Here is my code:

   private static void flush() {

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

    try {

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");  

      } catch (Exception e) {
          System.out.println("Class Not Found Exception:");
          System.out.println(e.getMessage());       
      }
+3
source share
5 answers
try {
 String driverName = "com.mysql.jdbc.Driver";
 Class.forName(driverName);

 String serverName = "localhost";
 String mydatabase = "hpdata";
 String url = "jdbc:mysql :// " + serverName + "/" + mydatabase; 

 String username = "root";
 String password = "123456";
 connection = DriverManager.getConnection(url, username, password);
} catch(Exception e) {
 // appropriate action
}
+2
source

Try downloading the driver before using it by including this line.

Class.forName("com.mysql.jdbc.Driver")
+1
source

, mysql-connector-java-<version-number>-bin.jar . , .

+1

, CLASSPATH. , , , , .

CLASSPATH, .

It matters if your application is designed for the web or desktop. Please tell us what is right for you.

UPDATE:

The correct way to install CLASSPATH for a desktop application is to use the -classpath option on the JVM at startup:

java -classpath .;<paths-to-your-JARs-separated-by-semi-colons>;<paths-to-the-root-of-package-trees> foo.YourCode
+1
source

After configuration, CLASSPATHcopy mysql-connector-java-5.1.16-binto these folders:

C:\Program Files\Java\jdk1.6.0_18\jre\lib\ext

and

C:\Program Files\Java\jre6\lib\ext
+1
source

Source: https://habr.com/ru/post/1780146/


All Articles