2017-01-29 100 views
0

如何在JDBC上爲Microsoft SQL Server設置AllowMultipleQueries?JDBC和Microsoft SQL Server /如何設置AllowMultipleQueries

我的連接字符串目前正在跟隨,但它不起作用。

private final String url = "jdbc:sqlserver://localhost:11435;databaseName=myDatabase;allowMultiQueries=true"; 
+0

爲什麼不使用存儲過程呢? – Rahul

+0

我需要執行:INSERT INTO ......; SELECT @@ IDENTITY AS [id]; – steelbull

+0

'PreparedStatement'使用'getGeneratedKeys()' –

回答

0

爲什麼不使用存儲過程呢?而不是設置allowMultiQueries你倒是應該使用存儲過程像下面

create procedure usp_data 
as 
begin 
INSERT INTO ......; 
SELECT @@IDENTITY AS [id]; 
end 

現在調用存儲過程從後面的代碼。如果需要,您也可以對過程進行參數化。查看此現有職位Multiple queries executed in java in single statement

+0

我。不喜歡這個解決方案,因爲我經常使用@@ IDENTITY,並且爲了每次使用,我需要創建新的過程: - /是否存在另一個獲得最新ID的好方案? – steelbull

+0

@steelbull,不需要創建新的過程,但需要調用proc而不是多個adhoc查詢 – Rahul

+0

THX @Rahul。MSSQL上的JDBC絕對不支持多個查詢? – steelbull

1

使用Microsoft的SQL Server JDBC驅動程序,您無需爲連接URL添加任何特殊內容,以便在單個execute中啓用多個語句。這工作得很好:

connectionUrl = "jdbc:sqlserver://localhost:52865;databaseName=myDb"; 
try (Connection conn = DriverManager.getConnection(connectionUrl, myUserID, myPassword)) { 
    System.out.printf("Driver version %s%n", conn.getMetaData().getDriverVersion()); 

    try (Statement st = conn.createStatement()) { 
     st.execute("CREATE TABLE #test (id INT IDENTITY PRIMARY KEY, textcol NVARCHAR(50))"); 
    } 

    String[] itemsToInsert = new String[] { "foo", "bar" }; 

    String sql = 
      "SET NOCOUNT ON;" + 
      "INSERT INTO #test (textcol) VALUES (?);" + 
      "SELECT @@IDENTITY;"; 
    try (PreparedStatement ps = conn.prepareStatement(sql)) { 
     for (String item : itemsToInsert) { 
      ps.setString(1, item); 
      try (ResultSet rs = ps.executeQuery()) { 
       rs.next(); 
       int newId = rs.getInt(1); 
       System.out.printf("'%s' inserted with id=%d%n", item, newId); 
      } 
     } 
    } 

} catch (Exception e) { 
    e.printStackTrace(System.err); 
} 

生產

Driver version 6.0.7728.100 
'foo' inserted with id=1 
'bar' inserted with id=2 

然而,在這種特定的情況下,它會更好地使用JDBC的內置支持檢索生成鍵:

String sql = "INSERT INTO #test (textcol) VALUES (?)"; 
try (PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) { 
    for (String item : itemsToInsert) { 
     ps.setString(1, item); 
     ps.executeUpdate(); 
     try (ResultSet rs = ps.getGeneratedKeys()) { 
      rs.next(); 
      int newId = rs.getInt(1); 
      System.out.printf("'%s' inserted with id=%d%n", item, newId); 
     } 
    } 
} 

生產完全相同的結果。