0

就像这里我想在修改数据库时禁用外键检查。

但是我无法让它工作。如果我试试这个:

jdbc:sqlserver://myserver:1433?sessionVariables=FOREIGN_KEY_CHECKS=0

它将尝试将整体1433?sessionVariables=FOREIGN_KEY_CHECKS=0作为端口号。

像这样尝试:

jdbc:sqlserver://myserver:1433;FOREIGN_KEY_CHECKS=0

也无济于事,它会建立连接,但会引发外键约束违规。

我已经查看了 JDBC 驱动程序上的 Microsoft API 并用谷歌搜索,但没有任何帮助。

有人知道解决方案吗?

4

1 回答 1

0

似乎这对于 MSSQL 是不可能的。URL的规范

jdbc:sqlserver://[serverName[\instanceName][:portNumber]];property=value[;property=value]]

这里不能添加会话变量,至少在我看来。

我的解决方案是使用语句启用和禁用数据库约束。

public static void resetDatabase(String dataSetFilename) throws DatabaseException {
    IDatabaseConnection connection = null;
    try {
        connection = getDatabaseConnection();
        disableDatabaseConstraints(connection);
        executeDatabaseReset(connection, dataSetFilename);
    } catch (Exception ex) {
        throw new DatabaseException(ex);
    } finally {
        enableDatabaseConstraints(connection);
    }
}

private static void disableDatabaseConstraints(IDatabaseConnection connection) throws DatabaseException {
    try {
        Statement disableConstraintsStatement = connection.getConnection().createStatement();
        disableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT ALL\"");
        disableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? DISABLE TRIGGER ALL\"");
    } catch (SQLException ex) {
        throw new DatabaseException(ex);
    }
}

private static void enableDatabaseConstraints(IDatabaseConnection connection) throws DatabaseException {
    try {
        Statement enableConstraintsStatement = connection.getConnection().createStatement();
        enableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? CHECK CONSTRAINT ALL\"");
        enableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? ENABLE TRIGGER ALL\"");
    } catch (SQLException ex) {
        throw new DatabaseException(ex);
    }
}
于 2014-01-27T16:02:48.163 回答