2014-05-03 98 views
1

即時嘗試連接到數據庫,但我得到這個錯誤。Java JDBC MySQL連接錯誤:ClassNotFoundException

這是代碼

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class JDBCInsertValues { 

    public static void main(String[] args) throws Exception { 

     Class.forName("com.mysqljdbc.Driver"); 
     Connection conn = DriverManager.getConnection(
       "jdbc:mysql://localhost:3306/Drivers"); 

     PreparedStatement statement = conn.prepareStatement("SELECT * fom employee"); 
     ResultSet result = statement.executeQuery(); 
     while(result.next()){ 
      System.out.println(result.getString(1)+ " "+ result.getString(2)); 
     } 
    } 
} 

,這是錯誤即時得到。

運行:位於項目庫

Exception in thread "main" java.lang.ClassNotFoundException: com.mysqljdbc.Driver 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372) 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) 
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) 
    at java.lang.Class.forName0(Native Method) 
    at java.lang.Class.forName(Class.java:259) 
    at JDBCInsertValues.main(JDBCInsertValues.java:14) 

Java Result: 1 
BUILD SUCCESSFUL (total time: 0 seconds) 

我有司機。

回答

0

驅動程序名稱似乎是錯誤的

嘗試

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

,而不是

Class.forName("com.mysqljdbc.Driver"); 
+0

我工作的猜測,但現在我得到另一個錯誤,這是異常線程「主」java.sql.SQLException:訪問被拒絕用戶'root'@'localhost'(使用密碼:YES)這是我用於連接的代碼Connection conn = DriverManager.getConnection( 「jdbc:mysql:// localhost:3306/Drivers」,「root」,「root」);任何想法爲什麼? – user3594235

+0

...或者完全省略'Class.forName'語句。這些日子通常不是必需的。 (合理的最新版本的Java使用不同的機制來加載JDBC驅動程序。) –

+0

@ user3594235如果這個答案解決了你最初的問題,你應該[接受](http://meta.stackexchange.com/a/5235/238021)它和然後[問一個新問題](http://stackoverflow.com/questions/ask),如果你現在有一個不同的問題,你需要解決。 –

0

我認爲你正在使用ANT。如果是這個問題,可能是你錯過了在build.xml中包含mysql庫

0

我也在我的代碼中發現了同樣的問題。在你的代碼必須做以下幾件事:

  1. 變化的代碼在main方法的第一行的Class.forName(「com.mysql.jdbc.Driver」)
  2. 現在提取的MySQL連接器/ J像mysql-connector-java-5.1.32.zip文件。
  3. 你將在文件夾mysql-connector-java-5.1.32中提取jar文件mysql-connector-java-5.1.32-bin.jar在步驟2中解壓
  4. 現在右擊你的項目,去Build路徑>>配置構建路徑>>庫選項卡>>添加外部JAR >>從文件夾中選擇mysql-connector-java-5.1.32-bin.jar mysql-connector-java-5.1.32
  5. 刷新並運行你的項目。我希望這些步驟將解決您的問題