在Java中创建SQLServerBulkCopy对象时出现连接错误

时间:2019-04-12 22:44:08

标签: java sql java-8 sql-server-2016 mssql-jdbc

在创建SQLServerBulkCopy对象时收到以下错误:

com.microsoft.sqlserver.jdbc.SQLServerException: Destination connection must be a connection from the Microsoft JDBC Driver for SQL Server.
  • 使用2016 SQL Server;
  • 使用SQL身份验证进行连接;
  • 使用mssql-jdbc-6.4.0.jre8.jar和JRE 1.8版本。

连接成功,但是SQLServerBulkCopy对象创建失败。不确定为什么该连接不是SQLServerConnection的实例。

用于创建连接和SQLServerBulkCopy对象的代码:


    public static Connection getConnection() throws Exception
    {
        String connectionUrl = "jdbc:sqlserver://" + serverName + ":1433;database=" + databaseName
                + ";user=xxxxxx;password=yyyyyyy";

        Connection connection = null;

        try
        {
            DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
            connection = DriverManager.getConnection(connectionUrl);
        }
        catch (Exception e)
        {
            throw new ODSException("Unable to create connection to SQL Server.", e);
        }

        return connection;
    }

    private void executeBCP() throws ODSException {
        //Create a Connection and SQLServerBulkCopy objects
        try (Connection connection = JDBCUtil.getConnection();
                SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connection))
        {
            boolean prevAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

    //further code...

        }
        catch (SQLException e)
        {
            bcpLogger.error(e);

            throw new ODSException("Error bulk copying data to SQL Server.", e);
        }

从SQLServerBulkCopy源代码中,我看到构造函数具有以下代码:

    public SQLServerBulkCopy(Connection connection) throws SQLServerException {
            loggerExternal.entering(loggerClassName, "SQLServerBulkCopy", connection);
            if (null == connection || !(connection instanceof SQLServerConnection)) {
                SQLServerException.makeFromDriverError(null, null, SQLServerException.getErrString("R_invalidDestConnection"), null, false);
            }

0 个答案:

没有答案