1. 程式人生 > >Java中利用QueryRunner批量更新資料

Java中利用QueryRunner批量更新資料

程式碼如下:

package com.accord.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;

import com.accord.entity.Pz;
import com.accord.entity.PzDoc;
import com.accord.util.JdbcConnUtil;

public class A {
	
	private static Connection conn = null;
	
	public static void main(String[] args) throws Exception {
		
		Pz pz = new Pz();
		pz.setFsid("ncab");
		pz.setFip("10.110.20.11");
		pz.setFuser("fa65cn");
		pz.setFpwd("facn65_");
		
		List<PzDoc> docLists = new ArrayList<PzDoc>();
		PzDoc pzDoc = new PzDoc();
		pzDoc.setId("202");
		docLists.add(pzDoc);
		PzDoc pzDoc2 = new PzDoc();
		pzDoc2.setId("203");
		docLists.add(pzDoc2);
		
		PzDoc pzDoc3 = new PzDoc();
		pzDoc3.setId("315");
		docLists.add(pzDoc3);
		
		PzDoc pzDoc4 = new PzDoc();
		pzDoc4.setId("322");
		docLists.add(pzDoc4);
		
		List<Integer> listIndex = new ArrayList<Integer>();
		listIndex.add(0);
		listIndex.add(1);
		listIndex.add(2);
		
		List<String> extvounoLists = new ArrayList<String>();
		extvounoLists.add("202_20126");
		extvounoLists.add("203_20136");
		extvounoLists.add("315_31156");
		
		updatePzDocDatasExtvouno(pz, listIndex, docLists, extvounoLists);
	}
	
	public static void updatePzDocDatasExtvouno(Pz pz, List<Integer> listIndex, List<PzDoc> docLists,List<String> extvounoLists) throws Exception {
		//定義個id集合
		List<String> idLists = new ArrayList<String>();
		for (int index : listIndex) {
			idLists.add(docLists.get(index).getId());
		}
		QueryRunner queryRunner = new QueryRunner(true);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dates = sdf.format(new Date());
		
		Object[][] params= new Object[idLists.size()][];
		for (int i = 0; i < idLists.size(); i++) {
			params[i] = new Object[3];
			params[i][0]=dates;
			params[i][1]=extvounoLists.get(i);
			params[i][2]=idLists.get(i);
		}
		conn = JdbcConnUtil.getJdbcConnect(pz);
		String sql = "update nc_ext_fa_ls_pz_adoc t set t.extvounodate=to_date(?,'yyyy-mm-dd'),t.extvouno=?,t.extvounoflag='1' "
				+ "where t.id=?";
		int result = 0;
		try {
			result = queryRunner.batch(conn, sql, params).length;
			if(result>0) {
				System.out.println("資料更新成功");
			}else {
				System.out.println("資料更新失敗");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			conn.close();
		}
	}
}