2017-03-08 73 views
-1

我的JDBC驅動程序有問題。我無法連接到我的SQL Server數據庫。測試下面的代碼:JDBC - java看不到已安裝的驅動程序

public class Test { 

public static void main(String[] args) { 

     Connection con = null; 
     String conUrl = "jdbc:sqlserver://localhost:1433; databaseName=mydb; user=root; password=psswd;"; 

    try { 
    con = DriverManager.getConnection(conUrl); 
    System.out.println("OK"); 
    } catch (Exception e) { e.printStackTrace(); } 
     finally { 
      if (con != null) try { con.close(); } catch(Exception e) {} 
     } 
}} 

當我嘗試運行這段代碼我仍然得到錯誤:

java.sql.sqlexception no suitable driver found for (..) 

我已經加入路徑sqljdbc4.jar到CLASSPATH變量和ENU \權威性\ x64的國產化路徑變量。我正在JRE 1.8,SQL Server 2014和Windows 7上工作。

+0

添加這些您所使用的IDE,你如何添加驅動程序路徑類路徑,請 – Satya

+0
+0

你如何運行你的代碼?另外:全局'classpath'變量已被棄用,不應使用。您應該在啓動應用程序時指定類路徑'java -cp sqljdbc4.jar; yourapp.jar測試' –

回答

-1

這是因爲您尚未加載驅動程序。只需修改現有的代碼

try { 
//this will load the driver 
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 

con = DriverManager.getConnection(conUrl); 
System.out.println("OK"); 
} catch (Exception e) { e.printStackTrace(); } 
    finally { 
     if (con != null) try { con.close(); } catch(Exception e) {} 
} 
+2

如果您有新的JDBC驅動程序(支持JDBC 4.0的驅動程序),則這不是必需的。我不知道OP使用的MS SQL Server驅動程序是否是JDBC 4.0驅動程序。 – Jesper

+0

自2006年以來,這不是必需的(除了上下文中具有驅動程序的Web應用程序)。 –

+0

@Mark Web應用程序通常使用JNDI,因此它們將從DataSource(不需要Class.forName)獲得連接。此外,類加載器並不總是加載驅動程序,即使它是類型4驅動程序,因此顯式調用Class.forName可能會有所幫助。 –