在oracle中一次執行多條語句
阿新 • • 發佈:2019-02-13
工作中需要一次執行多條語句,本來想直接使用sql拼接成一個字串進行批處理,原sql如下:
String sql = "";
for(int i=0; i<deviceInfo.getDevice_ip().length; i++){
if(deviceInfo.getDevice_ip()[i] != null && !deviceInfo.getDevice_ip()[i].equals("")){
String sqlu = "insert into tab_upperdevice (device_id,device_ip,port_type,shelf,frame,slot,port) values(' " +
id +
"','" + deviceInfo.getDevice_ip()[i] +
"','" + deviceInfo.getPort_type()[i] +
"','" + deviceInfo.getShelf()[i] +
"','" + deviceInfo.getFrame()[i] +
" ','" + deviceInfo.getSlot()[i] +
"','" + deviceInfo.getPort()[i] +"')" + ";";
sql = sql + sqlu;
}
}
發現執行不了,經過查詢資料,發現oracle需要加begin end;欄位才能執行多條語句。
修改後的sql如下:
begin
String sql = "";
for(int i=0; i<deviceInfo.getDevice_ip().length; i++){
if (deviceInfo.getDevice_ip()[i] != null && !deviceInfo.getDevice_ip()[i].equals("")){
String sqlu = "insert into tab_upperdevice (device_id,device_ip,port_type,shelf,frame,slot,port) values('" +
id +
"','" + deviceInfo.getDevice_ip()[i] +
"','" + deviceInfo.getPort_type()[i] +
"','" + deviceInfo.getShelf()[i] +
"','" + deviceInfo.getFrame()[i] +
"','" + deviceInfo.getSlot()[i] +
"','" + deviceInfo.getPort()[i] +"')" + ";";
sql = sql + sqlu;
}
}
end;
修改後的語句依然執行不了,不知道是啥原因。
最終解決方法是使用List來執行,程式碼:
List<String> sqluList = new ArrayList<String>();
for(int i=0; i<deviceInfo.getDevice_ip().length; i++){
if(deviceInfo.getDevice_ip()[i] != null && !deviceInfo.getDevice_ip()[i].equals("")){
String sqlu = "insert into tab_upperdevice (device_id,device_ip,port_type,shelf,frame,slot,port) values('" +
id +
"','" + deviceInfo.getDevice_ip()[i] +
"','" + deviceInfo.getPort_type()[i] +
"','" + deviceInfo.getShelf()[i] +
"','" + deviceInfo.getFrame()[i] +
"','" + deviceInfo.getSlot()[i] +
"','" + deviceInfo.getPort()[i] +"')";
sqluList.add(sqlu);
this.log.info("新增上聯裝置sql->" + sqlu);
}
}
之後把這個List傳給總的List:
List<String> sqlList = new ArrayList<String>();
sqlList.addAll(createUpperDeviceSql(deviceInfo, id));
然後把這個List轉成陣列傳給批處理執行:
String[] sqlArr = sqlList.toArray(new String[sqlList.size()]);
return jt.batchUpdate(sqlArr);