Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jdbc可以高效地与其他数据一起获得生成的密钥_Jdbc_Batch File - Fatal编程技术网

jdbc可以高效地与其他数据一起获得生成的密钥

jdbc可以高效地与其他数据一起获得生成的密钥,jdbc,batch-file,Jdbc,Batch File,在批量插入许多行之后,我希望检索生成的键及其相应的插入行。我如何有效地做到这一点?很自然,我可以使用statement.getGeneratedKeys根据生成的每个id查询数据库中的每一行,但这似乎很慢。下面的代码执行批插入,然后遍历表中的所有结果,但是我不想包含插入前表中已经存在的数据。 还有别的选择吗 public static void main(String[] args) throws Exception { Connection conn = getMySqlCon

在批量插入许多行之后,我希望检索生成的键及其相应的插入行。我如何有效地做到这一点?很自然,我可以使用statement.getGeneratedKeys根据生成的每个id查询数据库中的每一行,但这似乎很慢。下面的代码执行批插入,然后遍历表中的所有结果,但是我不想包含插入前表中已经存在的数据。 还有别的选择吗

public static void main(String[] args) throws Exception { Connection conn = getMySqlConnection(); ResultSet rs = null; Statement stmt = null; try { conn = getMySqlConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); conn.setAutoCommit(false); stmt.addBatch("INSERT INTO survey(id, name) VALUES('11', 'Alex')"); stmt.addBatch("INSERT INTO survey(id, name) VALUES('22', 'Mary')"); stmt.addBatch("INSERT INTO survey(id, name) VALUES('33', 'Bob')"); int[] updateCounts = stmt.executeBatch(); System.out.println(updateCounts); conn.commit(); rs = stmt.executeQuery("SELECT * FROM survey"); while (rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); System.out.println("id="+id +" name="+name); } } catch(BatchUpdateException b) { System.err.println("SQLException: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor error code: " + b.getErrorCode()); System.err.print("Update counts: "); int [] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor error code: " + ex.getErrorCode()); } catch(Exception e) { e.printStackTrace(); System.err.println("Exception: " + e.getMessage()); } finally { rs.close(); stmt.close(); conn.close(); } }
您有一个感兴趣的ID列表。您可以使用“id in…,…,”约束:

StringBuilder newIds = new StringBuilder();
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
  if (newIds.length() > 0)  newIds.append(',');
  newIds.append(rs.getInt(1));
}

if (newIds.length() > ) {
  rs = stmt.executeQuery("SELECT * FROM survey where id in ("+newIds+")");
  ...
}