问题描述
我正在使用带有单个查询的PreparedStatement插入多行:
I'm inserting multiple rows using a PreparedStatement with a single query:
String query = "insert into MyTable (a,b,c) values (?,?,?),(?,?,?),(?,?,?),(?,?,?)"; // insert 4 rows in a single query
PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
// .. here: loop to set all 4 x 3 values in my prepared statement
我想获取MSSQL DB生成的ID.我不确定要使用哪种execute
风格.
And I want to get the IDs generated by the MSSQL DB. I'm not sure which flavor of execute
to use.
execute()
方法未返回预期的ResultSet
:
boolean thingy = stmt.execute();
System.out.println("execute returned ", thingy); // false: meaning no result set
ResultSet result = stmt.getResultSet(); // result is null
executeUpdate()
方法仅返回一个ResultSet
:
int rowCount = stmt.executeUpdate();
System.out.println(rowCount + " rows updated"); // 4 rows updated
ResultSet result = stmt.getGeneratedKeys();
// there's only one result:
result.next(); // true
int ID1 = result.getInt(1); // good
result.next(); // false, no more rows
是否可以通过单个INSERT获得生成的ID?由于性能原因,我不想发送多个INSERT查询.
Is it possible to get the generated IDs with a single INSERT? I do not want to send multiple INSERT queries for performance reasons.
数据库:MS SQL Server 11(2012)
网址:jdbc:jtds:sqlserver://...
驱动程序:net.sourceforge.jtds.jdbc.Driver jtds版本1.3.1
DB: MS SQL Server 11 (2012)
URL: jdbc:jtds:sqlserver://...
Driver: net.sourceforge.jtds.jdbc.Driver jtds version 1.3.1
推荐答案
对于SQL Server 2008和更高版本,添加 OUTPUT子句似乎可以解决问题:
For SQL Server 2008 and later, adding an OUTPUT clause to the INSERT statement seems to do the trick:
try (Statement st = conn.createStatement()) {
// TEST ENVIRONMENT: in a real application, this would be our permanent table
st.execute("CREATE TABLE #tmp (id INT IDENTITY PRIMARY KEY, txtcol NVARCHAR(50))");
st.execute("INSERT INTO #tmp (txtcol) VALUES (N'existing data')");
st.execute("INSERT INTO #tmp (txtcol) VALUES (N'more existing data')");
}
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO #tmp (txtcol) ");
sb.append(" OUTPUT INSERTED.id ");
sb.append(" VALUES (?), (?), (?) ");
try (PreparedStatement ps = conn.prepareStatement(sb.toString())) {
ps.setString(1, "foo");
ps.setString(2, "bar");
ps.setString(3, "baz");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
}
产生
3
4
5
这篇关于JDBC如何从具有多个值查询的单个插入中获取所有生成的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!