简体   繁体   中英

cannot load JDBC Driver

I'm trying to understand JDBC API and in order to do so,I'm just writing some code to estabilish a connection to the DB. It seems that I can't... I'm trying to manually load the Driver for mysql DB,but even if I include the connector .jar in the classpath the compiler complains that it can't find the package com.mysql.

If,on the other hand,I omit the Class.forName() method, the code compiles but I get a hundreds Exception lines at runtime.

I'm compiling (and running) including the jar in the command line:

javac -cp [path to jar] DBTest.java

here's my code:

import java.sql.*;

class DBTest {
**strong text**
  static final String ADDRESS="jdbc:mysql://127.0.0.1:8888/customer";
  static final String USER="myuser";
  static final String PASSWORD="luca";

  public static void main(String[] args) {
    Connection conn=null;
    Statement stat=null;
    Class.forName("com.mysql.jdbc.Driver");
    try {
      conn=DriverManager.getConnection(ADDRESS,USER,PASSWORD);
      stat=conn.createStatement();
      String query="SELECT * FROM person";
      ResultSet result=stat.executeQuery(query);
      while (result.next()) {
        String name=result.getString("name");
        String surname=result.getString("surname");
        int id=result.getInt("id");
        String telephone=result.getString("telephone");
        System.out.println(id+": first name: "+name+" second name: "+surname+" tel: "+telephone);
      } 
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
    finally {
      try {
        conn.close();
        stat.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }  
  }

Edit:

with the double quotes it now compiles fine, but at runtime it says something like:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM