JDBC processor used prepared statements and parameters.

This commit is contained in:
Michael Hierweck 2013-06-20 16:21:31 +02:00
parent 632833308a
commit 6b85081efa

View File

@ -2,6 +2,7 @@ package de.hsadmin.core.qserv;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
@ -19,8 +20,34 @@ public class JDBCProcessor extends AbstractProcessor {
private String url;
private String user;
private String password;
private List<String> sql;
private List<SQL> list;
private String errorMsg;
class SQL {
private String statement;
private String[] params;
public SQL(String statement) {
super();
this.statement = statement;
}
public SQL(String statement, String[] params) {
super();
this.statement = statement;
this.params = params;
}
public String getStatement() {
return statement;
}
public String[] getParams() {
return params;
}
}
public JDBCProcessor(String driver, String url, String user, String password) {
this.driver = driver;
@ -36,9 +63,15 @@ public class JDBCProcessor extends AbstractProcessor {
}
public void addSQL(String sqlStatement) {
if (sql == null)
sql = new ArrayList<String>();
sql.add(sqlStatement);
if (list == null)
list = new ArrayList<SQL>();
list.add(new SQL(sqlStatement));
}
public void addSQL(String sqlStatement, String[] sqlParams) {
if (list == null)
list = new ArrayList<SQL>();
list.add(new SQL(sqlStatement, sqlParams));
}
public Object process() throws ProcessorException {
@ -57,19 +90,26 @@ public class JDBCProcessor extends AbstractProcessor {
password = config.getProperty("pgsqladmin.password");
}
if (user == null || password == null) {
throw new ProcessorException("database admin-user configuration failed");
throw new ProcessorException(
"database admin-user configuration failed");
}
try {
Class.forName(driver);
c = DriverManager.getConnection(url, user, password);
if (c == null)
throw new ProcessorException("cannot connect to '" + url + "'");
Statement s = c.createStatement();
for (String sqlStatement : sql) {
s.addBatch(sqlStatement);
System.out.println("SQL: " + sqlStatement);
for (SQL sql : list) {
PreparedStatement s = c.prepareStatement(sql.getStatement());
String[] params = sql.getParams();
if (params != null) {
for (int i = 0; i < params.length; i++) {
s.setString(i, params[i]);
}
}
System.out.println("SQL: " + sql.getStatement());
s.execute();
}
return s.executeBatch();
return null;
} catch (SQLException aSqlExc) {
Exception exc = aSqlExc.getNextException();
if (exc == null) {
@ -95,8 +135,8 @@ public class JDBCProcessor extends AbstractProcessor {
StringBuffer log = new StringBuffer("JDBCProcessor\n");
log.append(url);
log.append("\n");
for (String s : sql) {
log.append(s);
for (SQL s : list) {
log.append(s.getStatement());
log.append("\n");
}
log.append("Error: ");