日期:2014-05-18  浏览次数:20627 次

JSP 如何实现批量插入?
我现在要实现这么一个功能,同时要向数据库中插入多条数据,类似与工资录入
我在网上也查了   说是用什么循环语句   过滤器   由于刚接触jsp   这么一说我也是不明白   希望那位高手可以把代码列出来让我看看   谢谢   (发现分不是想给多少就给多少的,刚来,所以不是很多   不好意思啊   )

------解决方案--------------------
数据放在数组中,循环数组执行插入
------解决方案--------------------
<input type= "text " name= "a1 ">
<input type= "text " name= "a2 ">
<input type= "text " name= "a3 ">
<input type= "text " name= "a4 ">
<input type= "text " name= "a5 ">

for (int i=1;i <5;i++){
String aa = request.getParameter( "a "+i);
String SQL = "INSERT INTO table (a) VALUES ( ' " + aa + " ') "
}
------解决方案--------------------
PreparedStatement ps =
conn.prepareStatement( "INSERT into employees values (?, ?, ?) ");
for (n = 0; n < 100; n++) {
ps.setString(name[n]);
ps.setLong(id[n]);
ps.setInt(salary[n]);
ps.addBatch();
}
ps.executeBatch();

------解决方案--------------------
/**批量处理
*/
public int[] executeBatch(String strTempSQL) throws Exception
{
int []nCount;
try
{
String strSQL[]=strTempSQL.split( "; ");
conn.setAutoCommit(false);
if(stmt==null)
{
stmt = conn.createStatement();
}
stmt.clearBatch();
for(int i=0;i <strSQL.length;i++)
{
stmt.addBatch(strSQL[i]);
}
nCount=stmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
}
catch(Exception e)
{
conn.rollback();
conn.setAutoCommit(true);
throw new Exception( "批处理出错,请检查你的SQL语句 ");
}

return nCount;
}
------解决方案--------------------
循环得到数据在循环插入,也可以将所有的插入语句写在一个SQL语句里,然后一起来执行该SQL语句,一般来说,后者的执行效率要高。