JAVA中QueryRunner批量更新 避坑之一

import org.apache.commons.dbutils.QueryRunner; 

/**
	 * 上传失败的,把gxmlflag的值404  置为 空
	 * @param dj
	 * @param docIdList
	 * @throws Exception
	 */
	public static void updateDocDatas404ToNull(Dj dj, List docIdList) throws Exception {
		//定义个id集合
		List idLists = new ArrayList();
		for (String basdocid: docIdList) {
			idLists.add(basdocid);
		}
		Object[] idArr = new Object[idLists.size()];
		idLists.toArray(idArr);
		QueryRunner queryRunner = new QueryRunner(true);
		Object[][] params = new Object[idArr.length][1];
		for (int i = 0; i < idArr.length; i++) {
			params[i][0] = idArr[i];
		}
		conn = JdbcConnUtil.getJdbcConnect(dj); 
		
		/*String sql = "update fa_rec_pay_doc t set t.gxmlflag = null "
				+ "where t.gxmlflag = 404 ";*/
		
		
		//下面sql中的*应该写成具体的字段,由于这个表字段太多,就省去了!
		String sql = "update fa_rec_pay_doc t set t.gxmlflag = null "
				+ " where t.id = ? and t.gxmlflag = 404 ";
		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();
		}
	}

JAVA中使用QueryRunner批量处理的时候一定要注意:

如果docIdList集合为空,会把t.gxmlflag = 404的更新,不管id等于不等于; 

QueryAndUpdateDatas.updateDocDatas404ToNull(dj, docIdList);

 

切记!!!判断下集合的大小    

if(docIdList.size()>0) {
        QueryAndUpdateDatas.updateDocDatas404ToNull(dj, docIdList);
 }

 

public class JdbcConnUtil {
	private static String DRIVER = "oracle.jdbc.OracleDriver";
    private static Connection con = null;
    
    /*
     * 数据库连接,需要传入Dj参数
     */
    public static Connection getJdbcConnect(Object obj) throws Exception{
    	//反射
		Method method = obj.getClass().getDeclaredMethod("getFsid");
		method.setAccessible(true);
		String fsid = (String) method.invoke(obj);
		Method method2 = obj.getClass().getDeclaredMethod("getFip");
		method2.setAccessible(true);
		String ip = (String) method2.invoke(obj);
		Method method3 = obj.getClass().getDeclaredMethod("getFuser");
		method3.setAccessible(true);
		String user = (String) method3.invoke(obj);
		Method method4 = obj.getClass().getDeclaredMethod("getFpwd");
		method4.setAccessible(true);
		String password = (String) method4.invoke(obj);
    	String url = "jdbc:oracle:thin:@//" + ip + ":1521/" + fsid;
		Class.forName(DRIVER);
		con = DriverManager.getConnection(url,user,password);
		return con;          
    }

//关闭数据库连接
    public static void closeConnection(){
    	try {
			con.close();
			System.out.println("关闭成功");
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}

 

你可能感兴趣的:(Java)