java PreparedStatement sql批量更新

private static void test1() {
		String sql = "update USER00 set downbandwidth=?,moddate=?,modoperator=? where username=?";
		List list = new ArrayList();

		Object[] u1 = { Integer.valueOf(10),
				new Timestamp(new Date().getTime()), "zgx1", "ws80o" };
		Object[] u2 = { Integer.valueOf(11),
				new Timestamp(new Date().getTime()), "zgx2", "13ui65" };
		Object[] u3 = { Integer.valueOf(12),
				new Timestamp(new Date().getTime()), "zgx3", "yjl0" };
		Object[] u4 = { Integer.valueOf(13),
				new Timestamp(new Date().getTime()), "zgx4", "k08" };
		Object[] u5 = { Integer.valueOf(14),
				new Timestamp(new Date().getTime()), "zgx5", "z2o88e" };
		list.add(u1);
		list.add(u2);
		list.add(u3);
		list.add(u4);
		list.add(u5);

		JDBCUtils.batchUpdate(sql, list);
	}

日期类型字段使用java.util.Date类型无效,需要使用Timestamp类型

使用PreparedStatement.setObject,不能使用Java基本类型,必须使用它们相应的包装类

public static void batchUpdate(String sqlTemplate, List list) {
		Connection conn = getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sqlTemplate);
			conn.setAutoCommit(false);
			int size = list.size();
			Object[] o = null;
			for (int i = 0; i < size; i++) {
				o = list.get(i);
				for (int j = 0; j < o.length; j++) {
					ps.setObject(j + 1, o[j]);
				}
				ps.addBatch();
			}

			ps.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			closeAll(null, ps, conn);
		}
	}

username不存在,也会批量更新成功。


你可能感兴趣的:(编程开发)