Java批量插入、更新数据

Java的批量添加数据,多个字段同时添加多条数据,我不知道你遇到过没有。今天我们就以一个具体的实例来说一下Java的批量添加数据,面向的是Oracle数据库。

前台页面:

<span style="font-size:14px;"><body class="main_body"  scroll="no">
<div class="employee_gun_dong">
	<form name="webform" method="post">
			<div class="main_content_bg">
		     	<div class="main_content_title">
						<div id="baseinfo" onclick="activeTabPanel(1)" style="margin-right:2px;" class="tab1">基本信息</div>
	            		<div id="semsinfo" onclick="activeTabPanel(2)" style="margin-right:2px;" class="tab1" >页签1</div>
	            		<div id="changeinfo" onclick="activeTabPanel(3)"style="margin-right:2px;" class="tab1" >页签2</div>
	            		<div id="familyinfo" onclick="activeTabPanel(4)" style="margin-right:2px;" class="tab1" >页签3</div>
	            		<div id="changeinfo" onclick="activeTabPanel(5)"style="margin-right:2px;" class="tab1" >页签4</div>
	            		<div id="familyinfo" onclick="activeTabPanel(6)" style="margin-right:2px;" class="tab1" >页签5</div>
	            		<div id="familyinfo" onclick="activeTabPanel(7)" style="margin-right:2px;" class="tab2" >页签6</div>
		     	</div>
			</div>

			<div class="main_content_bg" id="bankCardDiv">
				<div class="main_middle_bg">
				<div class="main_content_title">信息展示
					<input id="addBank" type="button" value="新增一行"  class="modul_button_operate" onclick="addNewRow();" />
				</div>
						<div  class="main_table_bg">
						<table id="parttable" width='100%' border='0' cellspacing='1' cellpadding='0' class='content_table_list'>
								<tr>
									<th class='content_table_number'>序号</th>
									<th class='content_table_thnowarp'>属性1</th>
									<th class='content_table_thnowarp'>属性2</th>
									<th class='content_table_thnowarp'>属性3</th>
									<th class='content_table_thnowarp'>属性4</th>
									<th class='content_table_thnowarp'>属性5</th>
									<th class='content_table_thnowarp'>属性6</th>
									<th class='content_table_thnowarp'>属性7</th>
									<th class='content_table_thnowarp'>属性8</th>
									<th class='content_table_thnowarp'>属性9</th>
									<th class='content_table_thnowarp'>操作</th>
								</tr>
								<c:if test="${fn:length(personFamilyInfoList) > 0}">
								<c:forEach items="${personFamilyInfoList}" var="personFamilyInfoList" varStatus="st">	

								<tr>
									<!-- 序号 -->
									<td class="content_table_number">${st.count}
										<input type="hidden" name="personFamilyInfoList[${st.count-1}].SGuid" value="${personFamilyInfoList.SGuid}"/>
										<input type="hidden" name="personFamilyInfoList[${st.count-1}].SPersonGuid" value="${personFamilyInfoList.SPersonGuid}"/>
										<input type="hidden" name="personFamilyInfoList[${st.count-1}].SUnitGuid" value="${personFamilyInfoList.SUnitGuid }">
										<input type="hidden" name="personFamilyInfoList[${st.count-1}].isEnable" value="${personFamilyInfoList.isEnable }">
									</td>
									<!-- 属性1-->
									<td class="content_table_td_centernowrap">
										<input id="sFamilyName${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyName" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyName}">
									</td>
									<!-- 属性2-->
									<td class="content_table_td_centernowrap">
										<input id="sFamilyIdcardNo${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyIdcardNo" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyIdcardNo}">
									</td>
									<!-- 属性3-->
									<td class="content_table_td_centernowrap">
										<select id="iFamilySex${st.count-1}" name="personFamilyInfoList[${st.count-1}].IFamilySex">
											<zw:basedictlist itemCode="<%=Constants.I_PERSON_SEX %>" selectValue="${personFamilyInfoList.IFamilySex}"></zw:basedictlist>
										</select><font color="red">*</font>
									</td>
									<!-- 属性4-->
									<td class="content_table_td_centernowrap">
										<select id="sFamilyRelation${st.count-1}" name="personFamilyInfoList[${st.count-1}].SFamilyRelation">
											<zw:basedictlist itemCode="<%=Constants.S_FAMILY_RELATION %>" selectValue="${personFamilyInfoList.SFamilyRelation}"></zw:basedictlist>
										</select><font color="red">*</font>
									</td>
									<!-- 属性5-->
									<td class="content_table_td_centernowrap">
										<input id="sFamilyInsurancePlace${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyInsurancePlace" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyInsurancePlace}">
									</td>
									<!-- 属性6-->
									<td class='content_table_td_centernowrap'>
										<input id="sFamilyResidencePalce${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyResidencePalce" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyResidencePalce}">
									</td>
									<!-- 属性7-->
									<td class="content_table_td_centernowrap">
										<input id="sFamilyPhone${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyPhone" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyPhone}">
									</td>
									<!-- 属性8-->
									<td class="content_table_td_centernowrap">
										<input id="dDentifySucessDate${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].DDentifySucessDate" value="${personFamilyInfoList.DDentifySucessDate}" onfocus="WdatePicker()" notnull="true" vdisp="首次参保时间" class="content_content_input" size="18"  maxlength="18" style="width:70px;"/>
										<font color="red">*</font>
									</td>
									<!-- 属性9-->
									<td class="content_table_td_centernowrap">
										<input id="dDentifyLostDate${st.count-1}" type="text" name="personFamilyInfoList[${st.count - 1}].DDentifyLostDate" value="${personFamilyInfoList.DDentifyLostDate}" onfocus="WdatePicker()" notnull="true" vdisp="首次参保时间" class="content_content_input" size="18"  maxlength="18" style="width:70px;"/>
									</td>
									<td class='content_table_td_centernowrap'>取消</td>
								</tr>

								</c:forEach>
								</c:if>
							</table>
					</div>
				</div>
			</div>
			<div class="main_content_bg">
	     	<div class="main_content_title">
     			<table style="width:100%">
					<tr>
						<td  width="100%" align="center">
							<input id="btnNextstep" type="button" value="上一步" class="modul_button_operate" onclick="" />
							<input id="btnAdd" type="button" value="保存" class="modul_button_operate" onclick="saveOrUpdate()" />
							<input id="" type="button" value="完成" class="modul_button_operate" onclick="" />
							<input id="btnReturn" type="button" value="返回" class="modul_button_operate" onclick="" />
						</td>
					</tr>
				</table>
	     	</div>
	     </div>
	</form>
</div>
</body></span>

javascript函数:

<span style="font-family:KaiTi_GB2312;font-size:14px;"><script type="text/javascript">
	$(function(){
		loadCheck();
	});

	function loadCheck(){
		var trs = $('#parttable tr').length;
		if(trs == 1){
		addNewRow();
		}
	}

	//初始变量
	var num = 0;//页面计数变量
	var row = 1;//行增加计数变量
	var index = 2;//List列表计数变量
	function addNewRow(){
		var trNum = $('#parttable tr').length;
		if(trNum>1){
			row = trNum;
			num = trNum - 1;
		}
		var htmlText ='<tr>'
			+'<td class="content_table_number">'+row+'</td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="sFamilyName'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyName" class="content_content_input" maxlength="20"></td>' 

			+'<td class="content_table_td_centernowrap">'
			+'<input id="sFamilyIdcardNo'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyIdcardNo" class="content_content_input" maxlength="20"></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<select id="iFamilySex'+num+'" name="personFamilyInfoList['+num+'].IFamilySex">'
			+'<zw:basedictlist itemCode="2000" selectValue="personFamilyInfoList['+num+'].IFamilySex"></zw:basedictlist>'
			+'</select><font color="red">*</font></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<select id="sFamilyRelation'+num+'" name="personFamilyInfoList['+num+'].SFamilyRelation">'
			+'<zw:basedictlist itemCode="135" selectValue="personFamilyInfoList['+num+'].SFamilyRelation"></zw:basedictlist>'
			+'</select><font color="red">*</font></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="sFamilyInsurancePlace'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyInsurancePlace" class="content_content_input" maxlength="20"></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="sFamilyResidencePalce'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyResidencePalce" class="content_content_input" maxlength="20"></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="sFamilyPhone'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyPhone" class="content_content_input" maxlength="20"></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="dDentifySucessDate'+num+'" type="text" name="personFamilyInfoList['+num+'].DDentifySucessDate" onfocus="WdatePicker()" notnull="true" vdisp="首次参保时间" class="content_content_input" size="18"  maxlength="18" style="width:70px;"/><font color="red">*</font></td>'

			+'<td class="content_table_td_centernowrap">'
			+'<input id="dDentifyLostDate'+num+'" type="text" name="personFamilyInfoList['+num+'].DDentifyLostDate" onfocus="WdatePicker()" notnull="true" vdisp="首次参保时间" class="content_content_input" size="18"  maxlength="18" style="width:70px;"/></td>'		

			+'<td class="content_table_td_centernowrap">'
			+'<a onclick="delInsuranceInfo(this);">取消</a>'
			+'</td>'
			+'</tr>';
		$("#parttable").append(htmlText);
		num = num + 1;
		row += 1;
	}

	//删除动态列表
	function delInsuranceInfo(t){
		if(row>0){row=row-1} else{return false;}
		$(t).parent().parent().remove();
	}

	//保存或修改
	function saveOrUpdate(){
		$.ajax({
			url: "personFamilyInfo_addOrUpdatePersonFamilyInfo_include_json.action",
			type: "POST",
			data: jQuery(document.forms[0]).serializeArray(),
			success: function(resObj) {
				//判断返回值
				if (resObj.trim() == 'true') {
					Ext.MessageBox.alert("提示","保存成功",function(){

  					});
				}else if(resObj.trim() == 'update'){
					Ext.MessageBox.alert("提示","更新成功",function(){

					});
				} else {
					Ext.MessageBox.alert("提示","保存失败");
				}
			}
		});
	}			</span>
<span style="font-family:KaiTi_GB2312;font-size:14px;"></script></span>

后台添加方法:

<span style="font-family:KaiTi_GB2312;font-size:14px;">/**
	 * <p>Description: 批量添加多条信息</p>
	 * @param personFamilyInfoList 实体列表
	 * @return 布尔值,true为添加成功,否则为添加失败
	 * @throws Exception
	 * @author       : gaoying
	 * @update       :
	 * @date         : 2015-7-20
	 */
	public boolean addPersonFamilyInfo(List<PersonFamilyInfo> personFamilyInfoList) throws Exception{
		boolean bool = false;
		if(personFamilyInfoList.size()>0 && personFamilyInfoList != null){
			for(int i=0; i<personFamilyInfoList.size(); i++){
				String personFamilyID = UUIDHexGenerator.getUUID();
				String sunitGuid = "11111111";
				String spersonGuid = "0000000";
				if(personFamilyInfoList.get(i) != null){
					personFamilyInfoList.get(i).setSGuid(personFamilyID);
					personFamilyInfoList.get(i).setSUnitGuid(sunitGuid);
					personFamilyInfoList.get(i).setSPersonGuid(spersonGuid);
					personFamilyInfoList.get(i).setIsEnable(0);
					personFamilyInfoList.get(i).setDOperateDate(new Date());
					//设置系统的当前时间为生效时间,失效时间置为空
					personFamilyInfoList.get(i).setDDentifySucessDate(new Date());
					personFamilyInfoList.get(i).setDDentifyLostDate(null);
					try {
						String sGuidString = personFamilyInfoService.saveNeedPk(personFamilyInfoList.get(i)).toString();
						if(!"".equals(sGuidString)&&sGuidString.length()>0){
							bool = true;
						}else{
							System.out.println("供养亲属信息表 第"+i+"条信息存储失败!");
							bool = false;
							return bool;
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		}
		return bool;
	}</span>

后台更新方法:

<span style="font-family:KaiTi_GB2312;font-size:14px;">/**
	 * <p>Description: 批量更新信息</p>
	 * @param personFamilyInfolist 实体列表
	 * @param personId 人员id
	 * @return 布尔值,true代表更新成功,否则更新失败
	 * @throws Exception
	 * @author       : gaoying
	 * @update       :
	 * @date         : 2015-7-20
	 */
	public void updatePersonFamilyInfo(List<PersonFamilyInfo> personFamilyInfolist, String personId) throws Exception{
		//根据人员id查询页面有多少条数据
		List<PersonFamilyInfo> oldPersonFamilyInfolist = personFamilyInfoService.getPersonFamilyInfoByPersonId(personId);
		int num = oldPersonFamilyInfolist.size();
		if(personFamilyInfolist != null&&personFamilyInfolist.size() > 0){
			//检查页面的信息是否有修改,然后更新到数据库
			for(int i = 0; i<num; i++){
				try{
					//设置一个布尔值,如果变动字段设置为false,如果不变动则设置为true
					boolean bool = true;
					//判断哪些字段更改过
					if(!oldPersonFamilyInfolist.get(i).getSFamilyName().equals(personFamilyInfolist.get(i).getSFamilyName())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getSFamilyIdcardNo().equals(personFamilyInfolist.get(i).getSFamilyIdcardNo())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getIFamilySex().equals(personFamilyInfolist.get(i).getIFamilySex())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getSFamilyRelation().equals(personFamilyInfolist.get(i).getSFamilyRelation())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getSFamilyInsurancePlace().equals(personFamilyInfolist.get(i).getSFamilyInsurancePlace())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getSFamilyResidencePalce().equals(personFamilyInfolist.get(i).getSFamilyResidencePalce())){
						bool = false;
					}
					if(!oldPersonFamilyInfolist.get(i).getSFamilyPhone().equals(personFamilyInfolist.get(i).getSFamilyPhone())){
						bool = false;
					}
					System.out.println("未更改前时间:"+oldPersonFamilyInfolist.get(i).getDDentifySucessDate().getTime());
					System.out.println("更改后的时间:"+personFamilyInfolist.get(i).getDDentifySucessDate().getTime());
					if(oldPersonFamilyInfolist.get(i).getDDentifySucessDate().getTime() != personFamilyInfolist.get(i).getDDentifySucessDate().getTime()){
						bool = false;
					}

					if(bool == false){//证明字段更改过
						//更新数据前,要把原来没改动的数据复制一条,添加进数据库,把系统的当前时间设为该条数据的失效时间
						PersonFamilyInfo personFamilyInfo = new PersonFamilyInfo();

						BeanUtils.copyProperties(oldPersonFamilyInfolist.get(i), personFamilyInfo);
						System.out.println("该条数据主键:" + personFamilyInfo.getSGuid());
						personFamilyInfo.setSGuid(UUIDHexGenerator.getUUID());
						System.out.println("设置主键:" + personFamilyInfo.getSGuid());
						personFamilyInfo.setDOperateDate(new Date());
						//将当前保存数据库的是否有效置为1:无效
						personFamilyInfo.setIsEnable(1);
						personFamilyInfo.setDDentifyLostDate(new Date());						

						personFamilyInfoService.save(personFamilyInfo);

						//更新该条数据,把系统的当前时间设为系统的生效时间和操作时间,是否有效设为0:有效,失效时间为空
						personFamilyInfolist.get(i).setIsEnable(0);
						personFamilyInfolist.get(i).setDDentifySucessDate(new Date());
						personFamilyInfolist.get(i).setDOperateDate(new Date());
						personFamilyInfolist.get(i).setDDentifyLostDate(null);
						personFamilyInfoService.merge(personFamilyInfolist.get(i));
					}
				}catch (Exception e) {
					e.printStackTrace();
				} 

			}
		}</span>

这样,java多字段、多条数据批量添加的例子就完成了,主要要注意前台页面叠加出现多行的js函数和后台的添加和更新方法,用list接收,循环遍历进行添加。除此之外这里我想说一下下面这段代码:

<span style="font-family:KaiTi_GB2312;font-size:14px;">$(function(){
	loadCheck();
});</span>

它就是如下代码的缩写:

<span style="font-family:KaiTi_GB2312;font-size:14px;"> $(document).ready(function(){
        loadCheck();
});</span>

其实这个代码和下面的代码是一个意思:

<span style="font-family:KaiTi_GB2312;font-size:14px;">window.onload=function(){
       loadCheck();
}</span>

这样就不用在body的onload事件里面调用,只需要在js程序段里面编写就可以了。虽然下面的代码可以和上面两个互换,但他们之间又有不同。首先是执行时间不同,$(document).ready在页面框架下载完毕后就执行,而window.onload必须在页面全部加载完毕(包含图片下载)后才能执行。很明显前者的执行效率高于后者。再就是执行数量的不同,$(document).ready可以重复写多个,而且每次执行结果不同;而window.onload尽管可以执行多个,但仅输出最后一个执行结果,无法完成多个结果的输出。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-20 02:15:23

Java批量插入、更新数据的相关文章

java 批量插入10万条数据

for (int i = 0; i < 100000; i++) { dbHelper.insert("INSERT aaa(name) Values ('1')"); } 运行时间==780450ms conn = getConn(); // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数 conn.setAutoCommit(false); st = conn.createStatement(); long s

批量插入数据库数据,有则更新,无则追加

# 批量插入数据库数据,有则更新,无则追加import pymysqlimport numpy as npimport pandas as pdconn = pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd='root', db='py3_userinfo', charset='utf8' )# 游标cur = conn.cursor()df = pd.DataFrame([['合肥', 12, 110],['北京

ADO.NET 新特性之SqlBulkCopy(批量插入大量数据)

转自:http://blog.csdn.net/huaer1011/article/details/2312361 在.Net1.1中无论是对于批量插入整个DataTable中的所有数据到数据库中,还是进行不同数据源之间的迁移,都不是很方便.而在.Net2.0中,SQLClient命名空间下增加了几个新类帮助我们通过DataTable或DataReader批量迁移数据.数据源可以来自关系数据库或者XML文件,甚至WebService返回结果.其中最重要的一个类就是SqlBulkCopy类,使用它

SQLServer用存储过程实现插入更新数据

实现 1)有相同的数据,直接返回(返回值:0): 2)有主键相同,但是数据不同的数据,进行更新处理(返回值:2): 3)没有数据,进行插入数据处理(返回值:1). [创建存储过程] Create proc Insert_Update @Id varchar(20), @Name varchar(20), @Telephone varchar(20), @Address varchar(20), @Job varchar(20), @returnValue int output as declar

mysql 插入/更新数据

mysql 插入/更新数据 INSERT 语句 1.一次性列出全部字段的值,例如: INSERT INTO student VALUES('Chenqi','M', 29); INSERT INTO student VALUES('Bush','M', 60),('Obama', 'M', 45); 允许同时插入多个数据行: 2.只对部分字段赋值 INSERT INTO student(name, sex) VALUES ('Abby', 'F'),('Joseph', 'M'); 没有在INS

LoadRunner11之批量插入SQL数据~2

LoadRunner11之批量插入SQL数据 1.背景:数据库需要大量数据时,通过前台界面录入数据,是一个很麻烦的事情,这个时候可以借助工具来对数据库进行批量插入. 2.协议选择:我们选择的是LoadRunner11+webservice协议. 3.分析工作:(1)在录制之前,需要分析插入数据表字段的特性,是唯一还是随机,是否需要拼接等等 (2)表和表之间的关系,主外键以及关联的字段等 目的:为了更好的参数化数据,便于造的数据更加接近真实数据. 目前有2个表,student和stuclass c

java批量插入数据进数据库中

方式1: for循环,每一次进行一次插入数据. 方式2: jdbc的preparedStatement的batch操作 PreparedStatement.addBatch(); ...... PreparedStatement.executeBatch(); 一次最多不要超过50条:1.因为当你插入的时候 数据库已经锁定,然而如果你一次性插入太多会造成其他业务的等待.2.会造成内存的溢出 方式2的本质是:insert into table (a,b,c,d) values(av,bv,cv.d

java批量插入或更新的问题

在批量插入或者更新中,setXXX的时候字段类型必须一致.例如:在普通sql中 pstmt8.setBigDecimal(j ,xxx);可以写成pstmt8.setString(j,xxx.toString()); 但在批量插入时必须写成pstmt8.setBigDecimal(j,xxx);否则批处理会报提交中至少有一条不成功的问题.折腾一下午,终于搞好了.顺便记下来,方便参考.

mapper mysl实现批量插入 更新

1.批量插入 <insert id="insertConfirm" parameterType="java.util.List"> insert into `TableName`(id) values <foreach collection ="list" item="item" index= "index" separator =","> ('${item.id