如何在JDBC上为Microsoft SQL Server设置AllowMultipleQueries?
我的连接字符串当前正在关注,但它不起作用。
private final String url = "jdbc:sqlserver://localhost:11435;databaseName=myDatabase;allowMultiQueries=true";
答案 0 :(得分: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);
}
}
}
产生完全相同的结果。
答案 1 :(得分:0)
为什么不使用存储过程呢?您应该使用下面的存储过程
,而不是设置allowMultiQueries
create procedure usp_data
as
begin
INSERT INTO ......;
SELECT @@IDENTITY AS [id];
end
现在从后面的代码中调用该存储过程。如果需要,您也可以参数化该过程。请参阅此现有帖子Multiple queries executed in java in single statement