public class AssetsDao {
private static final String sql_insertMsg="insert into pandian_msg values(?,?,?,?,?,?,?,?,?)";
public final int SUCCESS=-1;
/**
* 批量插入数据库数据。
* @param asbList
* @return int[]
*/
@SuppressWarnings("unchecked")
public int insertMsgList(String xmldata){
Connection conn = null;
PreparedStatement stmt = null;
int res[] = null;
try {
// 建立连接
conn = DBUtil.getSQLSERVERConnection();
// 关闭事务自动提交
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql_insertMsg);
Long startTime = System.currentTimeMillis();
StringReader read=new StringReader(xmldata);
//创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
//创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
//通过输入源构造一个Document
org.jdom.Document doc = sb.build(source);
//取的根元素
org.jdom.Element root = doc.getRootElement();
//获取MEMBERLIST节点
org.jdom.Element memberEle=root.getChild("MEMBERLIST");
//得到数据数量
List mlist = memberEle.getChildren("MEMBER");
org.jdom.Element et=null;
for(int i=0;i<mlist.size();i++){
et=(org.jdom.Element) mlist.get(i);
stmt.setString(1, et.getAttribute("CODE").getValue());
stmt.setString(2, et.getAttribute("NAME").getValue());
stmt.setString(3, et.getAttribute("DEPARTMENT").getValue());
stmt.setString(4, et.getAttribute("VESTINGPEOPLE").getValue());
stmt.setDate(5, Date.valueOf(et.getAttribute("PURCHASETIME").getValue()));
stmt.setInt(6, Integer.parseInt(et.getAttribute("NETVALUE").getValue()));
stmt.setString(7, et.getAttribute("CLASSIFICATION").getValue());
stmt.setString(8, et.getAttribute("PROPERTYUNIT").getValue());
stmt.setDate(9, new Date(System.currentTimeMillis()));
// 把一个SQL命令加入命令列表
stmt.addBatch();
}
// 执行批量更新
res= stmt.executeBatch();
// 语句执行完毕,提交本事务
conn.commit();
Long endTime = System.currentTimeMillis();
System.out.println("用时:" + (endTime - startTime));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (JDOMException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} finally {
//关闭连接
DBUtil.closeConn(stmt, conn);
}
int i=0;
for(;i<res.length;i++){
if(res[i]==0)continue;
else{
i=SUCCESS;
break;
}
}
return i;
}
如上例所示,for(int i=0;i<mlist.size();i++){
et=(org.jdom.Element) mlist.get(i);
stmt.setString(1, et.getAttribute("CODE").getValue());
stmt.setString(2, et.getAttribute("NAME").getValue());
stmt.setString(3, et.getAttribute("DEPARTMENT").getValue());
stmt.setString(4, et.getAttribute("VESTINGPEOPLE").getValue());
stmt.setDate(5, Date.valueOf(et.getAttribute("PURCHASETIME").getValue()));
stmt.setInt(6, Integer.parseInt(et.getAttribute("NETVALUE").getValue()));
stmt.setString(7, et.getAttribute("CLASSIFICATION").getValue());
stmt.setString(8, et.getAttribute("PROPERTYUNIT").getValue());
stmt.setDate(9, new Date(System.currentTimeMillis()));
stmt.addBatch(); // 把一个SQL命令加入命令列表
}
res= stmt.executeBatch();// 执行批量更新
conn.commit();// 语句执行完毕,提交本事务