me.icymint.libra.jdbc.query.Executes Maven / Gradle / Ivy
package me.icymint.libra.jdbc.query;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringTokenizer;
import me.icymint.libra.jdbc.JdbcAccessException;
/**
* 批量执行无参数SQL语句。
*
* @author Daniel Yu
* @since 2013-3-14
*
*/
public class Executes extends AbstractExecute {
@Override
protected Statement createStatement(Connection conn, String sql) {
try {
return conn.createStatement();
} catch (SQLException e) {
throw new JdbcAccessException(e);
}
}
@Override
protected Void query(Statement u, String sql, Void p) {
String abc = null;
try {
if (sql.indexOf(';') < sql.length()) {
StringTokenizer st = new StringTokenizer(sql, ";");
while (st.hasMoreTokens()) {
abc = st.nextToken().trim();
if (!abc.isEmpty())
u.addBatch(abc);
}
try {
u.executeBatch();
} catch (BatchUpdateException e) {
// **这部分提取执行出错的SQL语句。
int[] x = e.getUpdateCounts();
for (int i = 0; i < x.length; i++) {
if (x[i] == Statement.EXECUTE_FAILED) {
st = new StringTokenizer(sql, ";");
int j = 0;
while (st.hasMoreTokens()) {
abc = st.nextToken().trim();
if (!abc.isEmpty()) {
if (j++ == i) {
break;
}
}
}
break;
}
}
throw e;
}
} else {
abc = sql;
u.executeUpdate(sql);
}
} catch (SQLException e) {
throw new JdbcAccessException("执行语句:" + abc, e);
}
return null;
}
}