我想在表中插入数组值来执行此任务我必须创建动态插入查询。如何执行它?
表中的列:
ExcelNumber, ExcelName, UserName, UserNum, Column5, Column6, Column7, Column8, Column9, Column10, Column11,Column12,..........
数组的前4列数据已修复,包含 ExcelNumber , ExcelName ,用户名, UserNum 这与表的前4列四列相同。 (数组名称为:arrayToBeInsert)。
数组包含任意数量的行和任意数量的列。
提前致谢。
示例:
[[101, EmployeeRecord101, Super@12, 214, ...........],
[101, EmployeeRecord101, Super@12, 214, ...........],
[101, EmployeeRecord101, Super@12, 214, ...........],
.
.
.
.
.]
代码:
try{
template.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
for(int i=0;i<arrayToBeInsert[0].length;i++){
String insertQuery ="INSERT INTO upload_temp (ExcelNumber, ExcelName, UserName, UserNum,";
.
.
.
.
}
return valueToBeReturn;/*HibernateCallback return*/
}
});
}catch(Exception e){
e.printStackTrace();
}
答案 0 :(得分:0)
template.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String insertQuery ="INSERT INTO upload_temp (ExcelNumber, ExcelName, UserName, UserNum,";
String columnsDeclaration = "";
for(int i=5;i<=arrayToBeInsert[0].length;i++) {
String col="Column"+i;
columnsDeclaration += col;
if(i <= (arrayToBeInsert[0].length-1)){
columnsDeclaration += ",";
}
}
insertQuery = insertQuery.concat(columnsDeclaration+") VALUES (");
String valueDeclaration = "";
for(int i=0;i<arrayToBeInsert.length;i++) {
for(int j=0;j<arrayToBeInsert[i].length;j++) {
String val=arrayToBeInsert[i][j];
valueDeclaration += "?";
if(j < (arrayToBeInsert[i].length-1)){
valueDeclaration += ",";
}
}
insertQuery = insertQuery.concat(valueDeclaration+");");
insertQuery=insertQuery.substring(0, insertQuery.indexOf(";")+1);
query=session.createSQLQuery(insertQuery);
for(int j=0;j<arrayToBeInsert[i].length;j++) {
query.setParameter(j, arrayToBeInsert[i][j]);
}
valueToBeReturn=query.executeUpdate();
}
return valueToBeReturn;/*HibernateCallback return*/
}
});