Pergunta

Exactly like here I want to disable the foreign key check when modifying the database.

However I can't get it to work. If I try this:

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

It will try to take the whole 1433?sessionVariables=FOREIGN_KEY_CHECKS=0 as a port number.

Trying it like this:

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

doesn't help either, it will setup the connection but throw a foreign-key constraint violation.

I already looked through the Microsoft API on the JDBC driver and googled, but it wasn't any help.

Does someone know a solution?

Foi útil?

Solução

It seems like this is not possible with MSSQL. The spec for the URL is

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

No session variables can be added here, at least it seems to me.

My solution is to en- and disable the database constraints using a statement.

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);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top