2014-04-24 218 views
0

我想用JDBC使用Java建立與MySQL數據庫的連接。java無法連接到jdbc

但是,當我嘗試做到這一點,我得到一些錯誤。 我敢肯定,這個問題並不是因爲MySQL服務器設置錯誤,因爲我試圖與MySQL Workbench連接,並且這可以工作。

我用這個Java代碼來設置德JDBC連接:

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


public class SQLConnection { 

    public static SQLConnection instance = new SQLConnection(); 
    public static String URL = "jdbc:mysql://localhost:3306/canbusdata"; 
    public static String USER= "root"; 
    public static String PSW = "root"; 

    public SQLConnection() 
    { 
    } 

    public static Connection getConnection() { 
     System.out.println("-------- MySQL JDBC Connection ------------\n"); 

     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
     } catch (ClassNotFoundException e) { 
      System.out.println("Where is your MySQL JDBC Driver?"); 
      e.printStackTrace(); 

     } 
     System.out.println("MySQL JDBC Driver Registered!"); 
     Connection connection = null; 

     try { 
      connection = DriverManager.getConnection(URL,USER,PSW); 

     } catch (SQLException e) { 
      System.out.println("Connection Failed! Check output console: \n"); 
      e.printStackTrace(); 

     } 

     return connection; 
    } 
} 

但我得到這個錯誤:

-------- MySQL JDBC Connection ------------ 

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 
Where is your MySQL JDBC Driver? 
MySQL JDBC Driver Registered! 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366) 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) 
Connection Failed! Check output console: 

    at java.security.AccessController.doPrivileged(Native Method) 
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425) 
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358) 
    at java.lang.Class.forName0(Native Method) 
    at java.lang.Class.forName(Class.java:190) 
    at SQLConnection.getConnection(SQLConnection.java:21) 
    at Start.ProcessData(Start.java:109) 
    at Start.main(Start.java:21) 
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/canbusdata 
    at java.sql.DriverManager.getConnection(DriverManager.java:596) 
    at java.sql.DriverManager.getConnection(DriverManager.java:215) 
    at SQLConnection.getConnection(SQLConnection.java:31) 
    at Start.ProcessData(Start.java:109) 
    at Start.main(Start.java:21) 
Exception in thread "main" java.lang.NullPointerException 
    at Start.ProcessData(Start.java:110) 
    at Start.main(Start.java:21) 
Java Result: 1 
+0

檢查你的類路徑。你從哪裏運行:IDE或提示? – jedison

+0

如果您需要一些建議,請粘貼您的類路徑設置(pom或類似)。 – jedison

+0

[Java連接與MySQL]可能的重複(http://stackoverflow.com/questions/2839321/java-connectivity-with-mysql) – demongolem

回答

2

看起來你沒有在你的項目中配置JDBC驅動程序。確保在運行它之前將它添加到類路徑中(通過命令行或基於IDE)。