2011-06-29 92 views
0
package javaapplication1; 
import java.sql.*; 
public class JavaApplication1{ 
    public static void main(String[] args) { 
    System.out.println("MySQL Connect Example."); 
    Connection conn = null; 
    String url = "jdbc:mysql://localhost:3306/TEST/ANKUR1"; 
    String dbName = "jdbctutorial"; 
    String driver = "com.mysql.jdbc.Driver"; 
    String userName = "root"; 
    String password = "root"; 
    try { 
    Class.forName(driver).newInstance(); 
    conn = DriverManager.getConnection("TEST1/ANKUR","root","school"); 
    System.out.println("Connected to the database"); 
    conn.close(); 
    System.out.println("Disconnected from database"); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
    } 
} 

我已經安裝了MySQL 5.5我的機器上,我在所需的文件夾複製Java的connector.jar文件。我的數據庫是test1,表是ankur。請參閱我正在使用此代碼來檢查與NetBeans 7的連接。是否有任何建議?錯誤代碼:java.sql.SQLException中:發現測試沒有合適的驅動程序/ ANKUR

+0

我知道有一些問題,但我想知道爲什麼會出現此錯誤? –

+0

您是否在項目中添加了mysql jar參考? –

回答

0

您實際在getConnection(...)中使用的URL是錯誤的。你不應該只輸入你想要的表格的名字。你需要一個完整的URL,以便JDBC系統知道它應該使用mysql驅動程序以及mysql驅動程序需要連接到的位置。

重新檢查您從中複製的示例,並查看它們使用「url」變量的位置。

0

的使用MySQL Connector/J驅動時JDBC URL format是:

的jdbc:mysql的:// [主持人] [,... failoverhost]:[?propertyName1] [口]/[數據庫] [= propertyValue1] [& propertyName2] [= propertyValue2] ...

因此,在你的情況下使用的實際URL應該是(如果安裝了數據庫在本地計算機上使用的名稱TEST和聽力在默認的MySQL端口3306上):

JDBC:MySQL的://本地主機:3306/TEST

,而不是下方。

TEST/ANKUR1

記住JDBC URL由所述DriverManager類用於確定哪些驅動器應該被用於連接到數據庫中,並且其中所述數據庫位於。一個不連接到JDBC中的表;而是連接到數據庫(或模式),然後對錶發出SELECT查詢。你的方法,因此,看起來像:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/TEST","root","school"); 
System.out.println("Connected to the database"); 
PreparedStatement pStmt = conn.prepareStatement("SELECT * FROM ANKUR"); 
ResultSet rs = pStmt.executeQuery(); 
... 
//Process the contents of the ResultSet 
... 
rs.close(); 
pStmt.close(); 
conn.close(); 

應當指出的是,它一個很好的做法,關閉在finally塊ResultSetPreparedStatementConnection對象。

相關問題