【问题标题】:JDBC connection to linked server到链接服务器的 JDBC 连接
【发布时间】:2015-11-17 14:34:18
【问题描述】:

我正在尝试从 Java 应用程序连接到我使用 MSSQL Server 创建的链接服务器。

网址字符串是

jdbc:sqlserver://172.15.230.11

查询是

SELECT * FROM OPENQUERY(172.15.230.11,'SELECT * FROM myTable WHERE 我的代码 = 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;
    }

【问题讨论】:

    标签: sql-server jdbc linked-server


    【解决方案1】:

    首先你必须确保你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;";
    

    【讨论】:

    • 谢谢。它没有使用 Windows 身份验证。使用相同的用户名和密码,我可以使用 sql server management studio 或 Navicat 登录,但相同的用户名和密码在我的应用程序中不起作用。
    • 也许如果你添加实际代码可以帮助找到问题
    猜你喜欢
    • 2016-04-28
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多