我尝试从Java应用程序连接到使用MSSQL Server创建的链接服务器。
网址字符串
JDBC:SQLSERVER://172.15.230.11
,查询是
SELECT * FROM OPENQUERY(172.15.230.11,' SELECT * FROM myTable WHERE myCode = 345')
但是当我运行程序时,会发生以下异常:
com.microsoft.sqlserver.jdbc.SQLServerException:用户' myUser'登录失败。
实际代码在这里:
private static final String DB_URL_LOCAL = "jdbc:sqlserver://172.15.230.11";
private static final String DB_USERNAME_LOCAL = "myUser";
private static final String DB_PASSWORD_LOCAL = "myPassword";
private static final String DB_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static String SQL_READ = "SELECT * FROM OPENQUERY(172.15.230.11,'SELECT * FROM myTable WHERE myCode = 345')";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(SQL_READ);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static Connection getConnection(){
Connection connection = null;
Properties properties = new Properties();
try {
Class.forName(DB_CLASS);
properties.setProperty("characterEncoding", "utf-8");
properties.setProperty("user", DB_USERNAME_LOCAL);
properties.setProperty("password", DB_PASSWORD_LOCAL);
connection = DriverManager.getConnection(DB_URL_LOCAL, properties);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
答案 0 :(得分:0)
首先,您必须确保enable remote connections到MSSQLserver。
然后确保您在连接中使用具有足够权限来查询架构的用户。
然后确保为JDBC驱动程序提供正确的源:
dbsource= "jdbc:sqlserver://IP:1433;database=MY_SCHEMA";
然后确保加载正确的JDBC驱动程序并使用适当的用户和密码
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dbCon = DriverManager.getConnection(dbsource, user, password);
最重要的是,如果您的数据库使用的是Windows身份验证,那么您可以使用'integratedSecurity':
dbsource= "jdbc:sqlserver://IP:1433;database=MY_SCHEMA;integratedSecurity=true;";