如何在JDBC上爲Microsoft SQL Server設置AllowMultipleQueries?JDBC和Microsoft SQL Server /如何設置AllowMultipleQueries
我的連接字符串目前正在跟隨,但它不起作用。
private final String url = "jdbc:sqlserver://localhost:11435;databaseName=myDatabase;allowMultiQueries=true";
如何在JDBC上爲Microsoft SQL Server設置AllowMultipleQueries?JDBC和Microsoft SQL Server /如何設置AllowMultipleQueries
我的連接字符串目前正在跟隨,但它不起作用。
private final String url = "jdbc:sqlserver://localhost:11435;databaseName=myDatabase;allowMultiQueries=true";
爲什麼不使用存儲過程呢?而不是設置allowMultiQueries
你倒是應該使用存儲過程像下面
create procedure usp_data
as
begin
INSERT INTO ......;
SELECT @@IDENTITY AS [id];
end
現在調用存儲過程從後面的代碼。如果需要,您也可以對過程進行參數化。查看此現有職位Multiple queries executed in java in single statement
使用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);
}
}
}
生產完全相同的結果。
爲什麼不使用存儲過程呢? – Rahul
我需要執行:INSERT INTO ......; SELECT @@ IDENTITY AS [id]; – steelbull
'PreparedStatement'使用'getGeneratedKeys()' –