Datax数据同步支持SqlServer 主键自增

允许写入的SQL

SET IDENTITY_INSERT table_name ON;

-- 插入数据,指定主键值
INSERT INTO table_name (id, column1, column2, ...)
VALUES (new_id_value, value1, value2, ...);

SET IDENTITY_INSERT table_name OFF;

写入插件处理

核心类:com.alibaba.datax.plugin.rdbms.writer.CommonRdbmsWriter

protected void doBatchInsert(Connection connection, List buffer)
        throws SQLException {
    PreparedStatement preparedStatement = null;
    Statement statementIdentify = null;
    try {
        statementIdentify = connection.createStatement();
        statementIdentify.execute(String.format("SET IDENTITY_INSERT %s ON", table));

        connection.setAutoCommit(false);
        preparedStatement = connection
                .prepareStatement(this.writeRecordSql);

        for (Record record : buffer) {
            preparedStatement = fillPreparedStatement(
                    preparedStatement, record);
            preparedStatement.addBatch();
        }
        preparedStatement.executeBatch();
        connection.commit();
    } catch (SQLException e) {
        LOG.warn("回滚此次写入, 采用每次写入一行方式提交. 因为:" + e.getMessage());
        connection.rollback();
        doOneInsert(connection, buffer);
    } catch (Exception e) {
        throw DataXException.asDataXException(
                DBUtilErrorCode.WRITE_DATA_ERROR, e);
    } finally {
        if (null != statementIdentify) {
            statementIdentify.execute(String.format("SET IDENTITY_INSERT %s OFF", table));
            try {
                statementIdentify.close();
            } catch (SQLException unused) {
            }
        }
        DBUtil.closeDBResources(preparedStatement, null);
    }
}

你可能感兴趣的:(数据迁移,sqlserver,数据库)