JDBC客户端可以在Microsoft SQL Server 2012上执行SET ARITHABORT ON吗?

时间:2014-10-26 09:16:30

标签: sql-server jdbc sql-optimization

我是否可以从使用Microsoft JDBC Driver 4.0的(远程)Java客户端以编程方式设置Microsoft SQL Server 2012选项,例如ARITHABORT?我注意到statement.execute("SET ARITHABORT ON")返回false并且预期效果似乎缺失,因此问题就出现了。

1 个答案:

答案 0 :(得分:2)

  

我是否可以从使用Microsoft JDBC Driver 4.0的(远程)Java客户端以编程方式设置Microsoft SQL Server 2012选项,例如ARITHABORT?

肯定是这样。代码

package com.example.sqlservertest;

import java.sql.*;

public class SqlServerTestMain {

    public static void main(String[] args) {
        String connectionUrl = "jdbc:sqlserver://localhost:52865;"
                + "databaseName=myDb;" + "integratedSecurity=true";
        try (Connection con = DriverManager.getConnection(connectionUrl)) {
            System.out.println("Connection established.");
            try (Statement stmt = con.createStatement()) {
                try (ResultSet rs = stmt.executeQuery("SELECT CONVERT(INT, SESSIONPROPERTY('ARITHABORT'))")) {
                    rs.next();
                    System.out.println(String.format(
                            "SESSIONPROPERTY('ARITHABORT') is %d",
                            rs.getInt(1)));
                }
                String sql = "SET ARITHABORT ON";
                System.out.println(sql);
                stmt.execute(sql);
                try (ResultSet rs = stmt.executeQuery("SELECT CONVERT(INT, SESSIONPROPERTY('ARITHABORT'))")) {
                    rs.next();
                    System.out.println(String.format(
                            "SESSIONPROPERTY('ARITHABORT') is %d",
                            rs.getInt(1)));
                }
                sql = "SET ARITHABORT OFF";
                System.out.println(sql);
                stmt.execute(sql);
                try (ResultSet rs = stmt.executeQuery("SELECT CONVERT(INT, SESSIONPROPERTY('ARITHABORT'))")) {
                    rs.next();
                    System.out.println(String.format(
                            "SESSIONPROPERTY('ARITHABORT') is %d",
                            rs.getInt(1)));
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

}

返回

Connection established.
SESSIONPROPERTY('ARITHABORT') is 0
SET ARITHABORT ON
SESSIONPROPERTY('ARITHABORT') is 1
SET ARITHABORT OFF
SESSIONPROPERTY('ARITHABORT') is 0

ARITHABORT状态应该在连接的生命周期内保持有效,除非其他一些代码对其进行更改。