连接到sql server windows身份验证

时间:2017-11-15 10:14:16

标签: java sql-server

我有一个sql server实例,

我可以连接sql autehntication

public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;";
     String userName = "sa"; 
     String password = "paquito";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = "); 
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}

但使用Windows身份验证

public static void main(String[] args) {
     Connection conn = null;
     String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     String url = "jdbc:sqlserver://localhost:1434;databasename=Test;integratedSecurity=true";
     String userName = "paco"; 
     String password = "";
     Statement stmt;
     try{
       Class.forName(driver);//.newInstance();
       conn = DriverManager.getConnection(url,userName,password);
       stmt = conn.createStatement();
       System.out.println("conectado = "); 
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
}

我接受了这个错误:

com.microsoft.sqlserver.jdbc.SQLServerException: Unable to open the "Test" database requested by the login. Login failed. Client connection ID: 577da72f-f0d4-4ac6-abab-243f0f84d0e3
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:279)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:99)

注意:在sql管理中,我可以连接sql身份验证和Windows身份验证

建议?

2 个答案:

答案 0 :(得分:0)

您可以在连接字符串中使用Integrated Security替换integratedSecurity并试试吗?

答案 1 :(得分:0)

不要指定用户名,它会从当前用户那里获得。

有关详细信息,请参阅https://www.connectionstrings.com/sql-server/