我无法使用 sqljdbc4.jar 从我的 Java 应用程序连接到 MSSQL Server 2012。
以下是我的代码:
public static void main(String[] args) {
String connectionUrl = "jdbc:sqlserver://172.16.0.4:1433;" +
"databaseName=PUC;user=admin;password=admin;instanceName=mssqlserver2012";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Patron";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
以下是错误:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'admin'. ClientConnectionId:1530f396-0935-4c41-92f1-016797a65edd
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:243)
at Main.main(Main.java:18)
注意:用户名和密码是正确的,我已经交叉检查了它们。我的 JDK 版本是 1.7 更新 21。当我通过更改连接字符串和驱动程序类来使用JTDS1.3.1 驱动程序时,如下所示:
String connectionUrl = "jdbc:jtds:sqlserver://172.16.0.4:1433/PUC;instance=mssqlserver2012;user=admin;password=admin";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
它可以工作,但为什么不能使用 Microsoft JDBC Driver 4.0 for SQL Server?