PreparedStatement 批量更新,插入数据到Oracle mysql

前端之家收集整理的这篇文章主要介绍了PreparedStatement 批量更新,插入数据到Oracle mysql前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. /**
  2. *更新数据库已有的customer信息
  3. *@paramList<CustomerBean>
  4. *@return
  5. */
  6. publicintupdateExistsInfo(List<CustomerBean>updateList){
  7. //查询sql语句
  8. Stringsql="updatet_customersetLICENSE_KEY=?,CORPORATE_NAME=?,INTEGRATED_CLASSIFICATION=?,BOSSHEAD=?,"+
  9. "CONTACT_PHONE=?,ORDER_FREQUENCY=?,CONTACT_ADDRESS=?,USER_ID=?whereCUSTOMER_ID=?";
  10. //插入需要的数据库对象
  11. Connectionconn=null;
  12. PreparedStatementpstmt=null;
  13. try{
  14. conn=newDBSource().getConnection();
  15. //设置事务属性
  16. conn.setAutoCommit(false);
  17. pstmt=conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
  18. for(CustomerBeancbean:updateList){
  19. pstmt.setString(1,cbean.getLicense_key());
  20. pstmt.setString(2,cbean.getCorporate_name());
  21. 3,cbean.getIntegrated_classification());
  22. 4,cbean.getBosshead());
  23. 5,cbean.getContact_phone());
  24. 6,cbean.getOrder_frequency());
  25. 7,cbean.getContact_address());
  26. pstmt.setInt(8,cbean.getUser_id());
  27. pstmt.setInt(9,cbean.getCustomer_id());
  28. @H_403_189@ pstmt.addBatch(); @H_403_189@ } @H_301_197@int[]tt=pstmt.executeBatch();
  29. System.out.println("update:"+tt.length);
  30. //提交,设置事务初始值
  31. conn.commit();
  32. conn.setAutoCommit(true);
  33. //插入成功,返回
  34. @H_301_197@returntt.length;
  35. }catch(sqlExceptionex){
  36. //提交失败,执行回滚操作
  37. conn.rollback();
  38. @H_403_189@ }catch(sqlExceptione){
  39. e.printStackTrace();
  40. System.err.println("updateExistsInfo回滚执行失败!!!");
  41. }
  42. ex.printStackTrace();
  43. System.err.println("updateExistsInfo执行失败");
  44. //插入失败返回标志0
  45. @H_301_197@return0;
  46. finally{
  47. //关闭资源
  48. if(pstmt!=null)pstmt.close();
  49. @H_301_197@if(conn!=null)conn.close();
  50. catch(sqlExceptione){
  51. e.printStackTrace();
  52. System.err.println("资源关闭失败!!!");
  53. /**
  54. *插入数据中没有的customer信息
  55. *@paramList<CustomerBean>
  56. *@return
  57. */
  58. @H_301_197@intinsertNewInfo(List<CustomerBean>insertList){
  59. Stringsql="insertintot_customer(CUSTOMER_ID,108); list-style-type:decimal-leading-zero; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "LICENSE_KEY,CORPORATE_NAME,INTEGRATED_CLASSIFICATION,BOSSHEAD,CONTACT_PHONE,"+
  60. "ORDER_FREQUENCY,CONTACT_ADDRESS,USER_ID,CUSTOMER_NUM,CUSTOMER_CODING,108); list-style-type:decimal-leading-zero; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "INVESTIGATION_TIME,SMS_REC_FLAG,WAP_FLAG,PRICE_GATHERING_FLAG,SOCIETY_STOCK_FLAG,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "REGION_TYPE)"+
  61. "VALUES(CUSTOMER.NEXTVAL,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "?,?,108); list-style-type:decimal-leading-zero; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "?,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "TO_DATE(?,'YYYY-MM-DD'),108); list-style-type:decimal-leading-zero; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> "?)";
  62. //插入需要的数据库对象
  63. Connectionconn= PreparedStatementpstmt=try{
  64. conn=newDBSource().getConnection();
  65. pstmt=conn.prepareStatement(sql,ResultSet.CONCUR_READ_ONLY);
  66. for(CustomerBeancbean:insertList){
  67. "gyyc00000");//
  68. 10,"95000000");//
  69. 11,getToday());
  70. 12,cbean.getSms_rec_flag());
  71. 13,cbean.getRegion_type());
  72. pstmt.addBatch();
  73. int[]tt=pstmt.executeBatch();
  74. System.out.println("insert:"+tt.length);
  75. //提交,设置事务初始值
  76. conn.commit();
  77. @H_301_197@true);
  78. //插入成功,返回
  79. returntt.length;
  80. @H_301_197@catch(sqlExceptionex){
  81. //提交失败,执行回滚操作
  82. conn.rollback();
  83. System.err.println("insertNewInfo回滚执行失败!!!");
  84. ex.printStackTrace();
  85. System.err.println("insertNewInfo执行失败");
  86. //插入失败返回标志0
  87. 0;
  88. @H_301_197@finally{
  89. //关闭资源
  90. @H_301_197@null)pstmt.close();
  91. null)conn.close();
  92. @H_403_189@ System.err.println("资源关闭失败!!!");
  93. }
使用Java JDBC基本的API批量插入数据到数据库
    @H_301_197@importjava.sql.Connection;
  1. importjava.sql.Statement;
  2. //...
  3. Connectionconnection=newgetConnection();
  4. Statementstatemenet=connection.createStatement();
  5. for(Employeeemployee:employees){
  6. Stringquery="insertintoemployee(name,city)values('"
  7. +employee.getName()+"','"+employee.getCity+"')";
  8. statemenet.addBatch(query);
  9. }
  10. statemenet.executeBatch();
  11. statemenet.close();
  12. connection.close();
  13. 请注意我们是如何从Employee对象中的数据动态创建查询并在批处理中添加,插入一气呵成。完美!是不是?
    等等......你必须思考什么关于sql注入?这样动态创建的查询sql注入是很容易的。并且每个插入查询每次都被编译。
    为什么不使用PreparedStatement而不是简单的声明。是的,这是个解决方案。下面是sql注入安全批处理。
    sql Injection Safe Batch - sql注入安全批处理
    思考一下下面代码:
    [java] view plain copy
      @H_301_197@importjava.sql.Connection;
    1. importjava.sql.PreparedStatement;
    2. //...
    3. Stringsql="insertintoemployee(name,city,phone)values(?,?)";
    4. Connectionconnection=newgetConnection();
    5. PreparedStatementps=connection.prepareStatement(sql);
    6. @H_301_197@for(Employeeemployee:employees){
    7. ps.setString( ps.setString(
    8. ps.addBatch();
    9. }
    10. ps.executeBatch();
    11. ps.close();
    12. connection.close();
    看看上面的代码。漂亮。我们使用的java.sql.PreparedStatement和在批处理中添加INSERT查询。这是你必须实现批量插入逻辑的解决方案,而不是上述Statement那个。
    这一解决方案仍然存在一个问题。考虑这样一个场景,在您想要插入到数据库使用批处理上万条记录。嗯,可能产生的OutOfMemoryError:

    java.lang.OutOfMemoryError: Java heap space
    com.MysqL.jdbc.ServerPreparedStatement$BatchedBindValues.<init>(ServerPreparedStatement.java:72)
    com.MysqL.jdbc.ServerPreparedStatement.addBatch(ServerPreparedStatement.java:330)
    org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:171)

    这是因为你试图在一个批次添加所有语句,并一次插入。最好的办法是将执行分批次。看看下面的解决方
    Smart Insert: Batch within Batch - 智能插入:将整批分批
    这是一个简单的解决方案。考虑批量大小为1000,每1000个查询语句为一批插入提交。
    copy
      Stringsql="insertintoemployee(name,?)";
    1. newgetConnection();
    2. PreparedStatementps=connection.prepareStatement(sql);
    3. finalintbatchSize=1000;
    4. @H_301_197@intcount=0;
    5. for(Employeeemployee:employees){
    6. ps.addBatch();
    7. @H_301_197@if(++count%batchSize==0){
    8. ps.executeBatch();
    9. }
    10. ps.executeBatch();//insertremainingrecords
    11. connection.close();
这才是理想的解决方案,它避免了sql注入和内存不足的问题。看看我们如何递增计数器计数,一旦BATCHSIZE 达到 1000,我们调用executeBatch()提交。

猜你在找的Oracle相关文章