MSSQL和JDBC读取DBCC USEROPTIONS

时间:2016-01-22 20:46:22

标签: sql-server jdbc spring-jdbc

我正在尝试阅读以下命令

返回的一些属性
DBCC USEROPTIONS

如何在JDBC中使用以下命令?

    List<ResultVO> list = getJdbcTemplate().query(sql, new ParameterizedBeanPropertyRowMapper<ResultVO>() {
        @Override
        public ResultVO mapRow(ResultSet rs, int rowNumber) throws SQLException {
            System.out.println(rowNumber);
            ResultVO v = new ResultVO();
            v.setSetOption(rs.getString(0));
            v.setValue(rs.getString(1));
            //--
            return v;
        }
    }, (List<String>) null);

它抛出异常如下:

Caused by: org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [SELECT DBCC USEROPTIONS]; The index 1 is out of range.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.
    at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:106)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)

1 个答案:

答案 0 :(得分:3)

错误消息的第一行表示您的代码尝试执行SQL语句

SELECT DBCC USEROPTIONS

但这不是有效的T-SQL语法。 T-SQL语句

DBCC USEROPTIONS

确实返回一个有效的ResultSet,如下面的vanilla JDBC代码所示:

try (Connection conn = DriverManager.getConnection(connectionUrl)) {
    try (
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery("DBCC USEROPTIONS")) {
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            System.out.printf("[%s]: %s%n", rsmd.getColumnName(i), rsmd.getColumnTypeName(i));
        }
        System.out.println();
        while (rs.next()) {
            System.out.printf("%s: %s%n", rs.getString(1), rs.getString(2));
        }
    }
} catch (Exception e) {
    e.printStackTrace(System.err);
}

产生

[Set Option]: nvarchar
[Value]: nvarchar

textsize: -1
language: us_english
dateformat: mdy
datefirst: 7
lock_timeout: -1
quoted_identifier: SET
ansi_null_dflt_on: SET
ansi_warnings: SET
ansi_padding: SET
ansi_nulls: SET
concat_null_yields_null: SET
isolation level: read committed

看起来您需要调整Spring JDBC代码才能执行DBCC USEROPTIONS