Can't execute sql statement after catching error - java

I catch the exception (I specially do mistake in SQL statement to get SQLException) when import records to database and I want in this catch update record in another table (in normal situation when we don't have an exception I also run this statement after importing records). But the problem is that record in another table not updated, however, in console I see that this updating successfull.
Firtsly, whem user import from FE records, in BE we get this POST-request in controller (It_tableController), after that call sevice (It_tableService) and service call DAO (It_tableDAO). And in DAO method I catch the SQLException (in It_tableDAO) and try to update record in another table (using import_sessionsDAO), but it doesn't works.
So why sql statement executes but not updates the record in catch block?
it_tableController.java:
#RequestMapping(value = "/*URL*/",
method = RequestMethod.POST)
#PreAuthorize("hasRole('USER')")
public ResponseEntity<List<EntityResponse>> addData(#PathVariable Integer originator_id,
#PathVariable Integer deployment_type_id,
#PathVariable Integer template_id,
#PathVariable String filename,
#RequestBody String[][] data,
#CurrentUser UserPrincipal currentUser) {
logger.info("Performing /*URL*/ POST request");
List<EntityResponse> response = it_tableService.addData(
deployment_type_id,
template_id,
originator_id,
filename,
currentUser.getId(),
currentUser.getUsername(),
data);
return new ResponseEntity<List<EntityResponse>>(response, HttpStatus.ACCEPTED);
}
It_tableService.java:
public List<EntityResponse> addData (
Integer deployment_type_id,
Integer template_id,
Integer originator_id,
String filename,
Long user_id,
String username,
String[][] data) {
if (!import_sessionsDAO.retrieveActiveImport_sessions(deployment_type_id).isEmpty())
{ return null; }
else {
Timestamp timestamp = import_sessionsDAO.insertImport_session(username, deployment_type_id, true, filename);
List<EntityResponse> responseItTable = new ArrayList<EntityResponse>();
responseItTable =
it_tableDAO.addData(deployment_type_id, template_id, originator_id, filename, user_id, username, data);
import_sessionsDAO.updateStatusOfImport_session(false, username, deployment_type_id, filename);
return responseItTable;
}
}
public Integer retrieveLastIdInTable(Integer deployment_type_id) {
Integer responseLastId = it_tableDAO.retrieveLastIdInTable(deployment_type_id);
return responseLastId;
}
it_tableDAO.java:
#Transactional
public List<EntityResponse> addData(Integer deployment_type_id,
Integer template_id,
Integer originator_id,
String filename,
Long user_id,
String username,
String[][] data) {
List<ColumnsNameModel> columnsName = getColumnsNameForDeploymentType(template_id);
List<EntityResponse> newRows = new ArrayList<EntityResponse>();
String tableName = getTableNameForDeploymentType(deployment_type_id);
String primaryKeyItTable = getPrimaryKeyItTableQuery(tableName);
// int columnsCountToItTable = getColumnsNameToItTable(columnsName, data);
for (int i = 1; i < data.length; i++) {
String INSERT_IT_TABLE_QUERY_part2 = "";
String updateFieldsOnConflict = "";
INSERT_IT_TABLE_QUERY = "INSERT INTO kddb." + tableName + " (";
for (int j = 0; j < data[0].length; j++) {
String column = "";
for (ColumnsNameModel columnName: columnsName) {
if (Objects.equals(columnName.getSource_field_name(), data[0][j]) ) {
column = columnName.getField_name_it_table();
if (j == 0 ) {
INSERT_IT_TABLE_QUERY += column;
updateFieldsOnConflict += column + "=EXCLUDED." + column;
}
else {
INSERT_IT_TABLE_QUERY += ", " + column;
updateFieldsOnConflict += ", " + column + "=EXCLUDED." + column;
}
INSERT_IT_TABLE_QUERY_part2 += ConcatinateToQuery(data[i][j], j);
}
}
}
updateFieldsOnConflict += ", import_user_id=EXCLUDED.import_user_id"+
", import_date=EXCLUDED.import_date"+
", import_file=EXCLUDED.import_file";
INSERT_IT_TABLE_QUERY += ", import_user_id, import_date, import_file)\n VALUES (";
INSERT_IT_TABLE_QUERY += INSERT_IT_TABLE_QUERY_part2;
INSERT_IT_TABLE_QUERY += ", " + user_id + ", \'" + new java.sql.Timestamp(new java.util.Date().getTime()) + "\', \'"
+ filename + "\'";
String uniqueKey = getUniqueKeyItTableQuery(tableName);
if (!Objects.equals(uniqueKey, null)) {
INSERT_IT_TABLE_QUERY += ") \n ON CONFLICT (" + uniqueKey + ") DO UPDATE SET \n" + updateFieldsOnConflict;
}
else {
INSERT_IT_TABLE_QUERY += ") \n ON CONFLICT (" + primaryKeyItTable + ") DO UPDATE SET \n" + updateFieldsOnConflict;
}
GeneratedKeyHolder holder = new GeneratedKeyHolder();
try {
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(INSERT_IT_TABLE_QUERY, Statement.RETURN_GENERATED_KEYS);
return statement;
}
}, holder);
GeneratedKeyHolder holder = new GeneratedKeyHolder();
try {
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(INSERT_IT_TABLE_QUERY, Statement.RETURN_GENERATED_KEYS);
return statement;
}
}, holder);
} catch (Exception e) {
/* ============ THIS STATEMENT NOT UPDATE THE TABLE */
import_sessionsDAO.updateStatusOfImport_session(false, username, deployment_type_id, filename);
logger.info("++++++++++++++++++++++++++++++++++++++++");
}
/* some another actions */
return newRows;
}
import_sessionsDAO.java:
private static String UPDATE_STATUS_OF_IMPORT_SESSION =
"\n UPDATE kddb.import_sessions SET running_status = ? \n" +
" WHERE username = ? AND deployment_type_id = ? AND \n" +
" filename = ?; ";
public void updateStatusOfImport_session(Boolean running_status, String username, Integer deployment_type_id, String filename) {
logger.info(UPDATE_STATUS_OF_IMPORT_SESSION);
jdbcTemplate.update(UPDATE_STATUS_OF_IMPORT_SESSION,
running_status,
username,
deployment_type_id,
filename);
logger.info("Successfully update a status (set {}) of record with parameters: username={} deployment_type_id={} filename={}",
running_status,
username,
deployment_type_id,
filename);
}

Related

out of memory when trying to select data from oracle database and insert it into sqlite

we get out of memory (the process go up and consumes %100 of ram) trying to select data and insert it into SQLite DB, the program written in java, and the data are so big, we even made pagination for it, it selects 100000 rows and inserts it into SQLite database, to figure out the problem, we commented out all line from the code that insert the data, and we saw that consumption of ram stop's at %6
package dbex;
import java.sql.*;
import java.util.ArrayList;
public class DBEX {
String url = "jdbc:oracle:thin:#192.168.120.46:1521:db";
String user = "dbuser";
String password = "dbpass";
ArrayList<Table> Tales = new ArrayList<>();
public static void main(String[] args) {
DBEX db = new DBEX();
db.CreateDB();
}
public int CountRecords(String table) {
int result = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection getCountCon = DriverManager.getConnection(url, user, password);
Statement CountSt = getCountCon.createStatement();
ResultSet countRs = CountSt.executeQuery("SELECT COUNT(*) as num FROM " + table);
while (countRs.next()) {
result = countRs.getInt("num");
}
} catch (Exception ex) {
}
return result;
}
public void dumpData() {
try {
int incrementRecord = 100000;
Class.forName("org.sqlite.JDBC");
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Table table = null;
ArrayList<String> columns = new ArrayList<>();
Connection getDataCon = DriverManager.getConnection(url, user, password);
getDataCon.setAutoCommit(false);
Statement dataSt = getDataCon.createStatement();
dataSt.setFetchSize(incrementRecord);
ResultSet dataRs = null;
Connection LiteInsertCon = DriverManager.getConnection("jdbc:sqlite:" + "DBEX" + ".db");
LiteInsertCon.setAutoCommit(false);
PreparedStatement insertStatement = null;
int numRecord = 0;
for (int i = 0; i < Tales.size(); i++) {
table = Tales.get(i);
String tableName = table.name;
System.out.println("table::" + tableName);
System.out.println("Dumping data from " + tableName);
String InsertSQL = "INSERT INTO " + tableName + " ( ";
String vals = "VALUES (";
String selectSQL = "SELECT * FROM ( SELECT b.*, ROWNUM RN FROM ( SELECT ";
System.out.println("geting column name...");
columns = table.Columns;
for (int j = 0; j < columns.size(); j++) {
String columnName = columns.get(j);
if (j == 0) {
vals += " ? ";
InsertSQL += columnName + " ";
selectSQL += columnName + " ";
}else {
InsertSQL += " , " + columnName + " ";
vals += ", ? ";
selectSQL += " , " + columnName + " ";
}
}
System.out.println("Number of column of table " + tableName + " is " + columns.size());
vals += ")";
InsertSQL += ")" + vals;
selectSQL += "FROM " + tableName + " ORDER BY "+table.primary_key+" ASC ) b WHERE ROWNUM <= :TO ) WHERE RN > :FROM ";
System.out.println(selectSQL);
System.out.println(InsertSQL);
int parIndex = 0;
String colName = null;
String data = null;
numRecord = CountRecords(tableName);
int from = 0;
int to = incrementRecord;
if (to > numRecord) {
System.out.println("Table data is less than "+incrementRecord+" geting all data "+numRecord+" " );
dataRs = dataSt.executeQuery(selectSQL.replace(":TO", numRecord + "").replace(":FROM", "0"));
while (dataRs.next()) {
insertStatement = LiteInsertCon.prepareStatement(InsertSQL);
insertStatement.setFetchSize(incrementRecord);
for (; parIndex < columns.size(); parIndex++) {
colName = columns.get(parIndex);
data = dataRs.getString(colName);
if (data != null) {
insertStatement.setString(parIndex + 1, data);
} else {
insertStatement.setString(parIndex + 1, " ");
}
parIndex++;
}
parIndex = 0;
insertStatement.executeUpdate();
insertStatement = null;
}
} else {
while (numRecord >= to) {
System.out.println("page "+(to/incrementRecord)+" of "+(numRecord/incrementRecord) );
dataRs = dataSt.executeQuery(selectSQL.replace(":TO", to + "").replace(":FROM", from+""));
while (dataRs.next()) {
insertStatement = LiteInsertCon.prepareStatement(InsertSQL);
insertStatement.setFetchSize(incrementRecord);
for (; parIndex < columns.size(); parIndex++) {
colName = columns.get(parIndex);
data = dataRs.getString(colName);
if (data != null) {
insertStatement.setString(parIndex + 1, data);
} else {
insertStatement.setString(parIndex + 1, " ");
}
parIndex++;
}
parIndex = 0;
insertStatement.executeUpdate();
insertStatement = null;
}
dataRs=null;
from = to;
to += incrementRecord;
System.gc();
}
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
class Table {
public String name;
public String primary_key;
ArrayList< String> Columns = new ArrayList<>();
public Table(String name, String primary_key, ArrayList< String> Columns) {
this.name = name;
this.primary_key = primary_key;
this.Columns = Columns;
}
}
public void CreateDB() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Oracle JDBC driver found");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection getTableCon = DriverManager.getConnection(url, user, password);
Connection getColumnCon = DriverManager.getConnection(url, user, password);
Connection getKeyCon = DriverManager.getConnection(url, user, password);
System.out.println("connected to database");
Statement getTableSt = getTableCon.createStatement();
PreparedStatement getColumnSt = getColumnCon.prepareStatement("SELECT DISTINCT column_name FROM all_tab_cols WHERE table_name = ? ");
PreparedStatement getKeySt = getKeyCon.prepareStatement("SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = ? AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position");
ResultSet getTableRs = getTableSt.executeQuery("SELECT * FROM all_tables WHERE OWNER not in('SYS','OUTLN','SYSTEM')");
ResultSet getColumnRs;
ResultSet getKeyRs;
Class.forName("org.sqlite.JDBC");
System.out.println("Sqlite JDBC driver found");
Connection LiteCreateTableCon = null;
LiteCreateTableCon = DriverManager.getConnection("jdbc:sqlite:" + "DBEX" + ".db");
Statement statement = LiteCreateTableCon.createStatement();
String keyName = "";
while (getTableRs.next()) {
String tableName = getTableRs.getString("table_name");
System.out.println("table: " + tableName);
getColumnSt.setString(1, tableName);
System.out.println("SELECT * FROM all_tab_cols WHERE table_name = " + tableName + "");
getColumnRs = getColumnSt.executeQuery();
String createTableSQL = "create table if not exists " + tableName + " ( ";
int index = 0;
ArrayList<String> Columns = new ArrayList<>();
while (getColumnRs.next()){
String columnName = getColumnRs.getString("column_name");
Columns.add(columnName);
System.out.println("column: " + columnName);
if (index == 0) {
createTableSQL += columnName + " string";
} else {
createTableSQL += " , " + columnName + " string";
}
index++;
}
createTableSQL += ")";
System.out.println(createTableSQL);
statement.executeUpdate(createTableSQL);
getKeySt.setString(1, tableName);
getKeyRs = getKeySt.executeQuery();
keyName = "1";
while (getKeyRs.next()) {
keyName = getKeyRs.getString("column_name");
}
Tales.add(new Table(tableName, keyName, Columns));
}
getTableCon.close();
getColumnCon.close();
getKeyCon.close();
System.out.println("All table created...");
}catch (Exception ex) {
System.out.println(ex.toString());
}
dumpData();
}
}
You need to issue/excute commit on SQLite after inserting every batch of records.
And try to come-up with suitable batch size (may be 100).

How can I search a customer by full name?

I'm creating a method wherein a user can search a customer either by first name, last name, or full name. the search bar only shows the result if it's by first or last name but when I try searching a customer by full name the record won't show.
Here's my code:
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
sqlSearch = sql + " WHERE firstName LIKE '%" + keyword + "%' AND lastName LIKE '%" + keyword + "%'";
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
Your queries should be:
Select * FROM `Customer`
WHERE `firstName` LIKE '%" + keyword + "%' OR `lastName` LIKE '%" + keyword + "%'"
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
String[] keywordArray=keyword.split(" ");
if(keywordArray.length>1) {
// matching full Name
sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' AND lastName LIKE '%" + keywordArray[1].trim() + "%'";
}else {
// matching firstName or lastName
sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' OR lastName LIKE '%" + keywordArray[0].trim() + "%'";
}
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
sqlSearch = sql + " WHERE LOCATE(firstName ,'" + keyword + "')>=0 AND LOCATE(lastName ,'" + keyword + "')>=0";
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}

How to add double quotes to the output values in a Resultset when the column datatype is String?

I am trying to run the below query and insert the output of it into another table (postgres db):
String ssnQuery = "SELECT period_year, period_name, period_num, NULL as count_of_issues,
ledger_id,
balancing_segment,
Count(*) AS count_of_account_segments,
Sum(accounted_period_net_dr) AS balance_accounted_period_net_dr,
Sum(accounted_period_net_cr) AS balance_accounted_period_net_cr,
Round(Sum(accounted_period_net_dr_cr)) AS balance_accounted_period_net_dr_cr_diff,
Sum(entered_period_net_dr) AS balance_entered_period_net_dr,
Sum(entered_period_net_cr) AS balance_entered_period_net_cr,
Round(Sum(entered_period_net_dr_cr)) AS balance_entered_period_net_dr_cr_diff,
Sum(begin_balance_dr) AS begin_balance_dr,
Sum(begin_balance_cr) AS begin_balance_cr,
Round(Sum(net_beginning_balance)) AS net_beginning_balance,
Round(Sum(net_closing_balance)) AS net_closing_balance
FROM schema.tablename";
try {
pstmnt = financeConnection.prepareStatement(ssnQuery);
rs = pstmnt.executeQuery();
rsmd = rs.getMetaData();
for(int i=1; i<=rsmd.getColumnCount(); i++) {
columnNames.add(rsmd.getColumnName(i));
if(i == 1) {
queryColumns = rsmd.getColumnName(i);
} else if(i<7) {
queryColumns += ", " + rsmd.getColumnName(i);
} else {
queryColumns += ", value_" + (i-7);
}
}
while (rs.next()) {
queryValues = " ";
for(String colname: columnNames) {
if(queryValues.isEmpty()) {
queryValues = rs.getString(colname);
} else {
queryValues += rs.getString(colname) + ", ";
}
}
remCommas = queryValues.replaceAll(", $", "");
insertQuery = "INSERT INTO bdmerge.gen_audit_func_hive_results (run_id, run_date, run_date_ist" + queryColumns + ") VALUES (" + runid +"," + utcTimeStamp + "," + istTimeStamp + "," + remCommas + ")";
System.out.println("Final Insert query: " + insertQuery);
}
} catch (SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
To insert the output of above query, I formed the insert query according the column names in the destination table as below:
INSERT INTO schema.destinationTable (run_id, run_date, run_date_ist, source_system_type, source_system, module, source_table_name, period_year, period_name, period_num, count_of_issues, count_of_accounted_issues, count_of_entered_issues, value_0, value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, value_12) VALUES (781,2018-11-12 08:15:32.0,2018-11-12 13:45:32.0, 2018, OCT-18, 10, null, 1, 1, 2073, ATRS, 6135, 6.2778220466107E11, 6.277946274560101E11, -1.2422795E7, 5.929031383587201E11, 5.9291556115366E11, -1.2422795E7, 3.931397937759116E13, 3.9313979377591164E13, 0.0)
But the destination table's columns:
run_id, count_of_issues, count_of_accounted_issues, count_of_entered_issues
are in numeric format (working on postgres db) and all others are varchar(1000).
In order to insert the varchar data, I need to enclose the column values from value_0 till value_12 in double quotes.
Without properly modifying the data, I am getting SQLException while inserting which is expected.
Is there any way I can just enclose those varchar column values from the resultSet in double quotes and insert them into destination table?
You need to add double quotes to the string values; Use Escape characters, like this:
String quotedStr = "Non Quoted," + " \"Quoted\".";
Modifying your code to address the problem:
while (rs.next()) {
queryValues = " ";
int i = 0;
for(String colname: columnNames) {
if(queryValues.isEmpty()) {
queryValues = rs.getString(colname);
} else {
if (i >= 7)
queryValues += "\"" + rs.getString(colname) +"\"" + ", ";
}
else
queryValues += rs.getString(colname) + ", ";
i++;
}

Java PostgreSQL arrayList<Object[]> insert code- applying to any number of colums

I've got a method in Java for inserting an ArrayList into PostgreSQL.
public void postgreSQLInsert(String tblname, String col1, String col2, String col3) throws SQLException, IOException, InterruptedException {
ArrayList<Object[]> insertList = voltdbresultarray;
if (insertList == null) {
} else {
for (Object[] columnValues : insertList) {
try {
System.out.println(columnValues[0]);
System.out.println(columnValues[1]);
System.out.println(columnValues[2]);
String sql = "INSERT INTO " + tblname + "(" + col1 + "," + col2 + "," + col3 + ") " + "VALUES (" + columnValues[0] + ", '" + columnValues[1] + "', " + columnValues[2] + " );";
postgresStmt.executeUpdate(sql);
} catch (PSQLException e) {
System.out.println("Duplicate!");
continue;
}
}
}
}
Col1, col2, and col3 are all column name strings created elsewhere, and voltdbresultarray is a static array given values earlier. It all works fine, but only for object arrays with three columns. I'd like to make it applicable to object arrays with any number of columns, but I can't figure out how. Is there a way to have it take any number of column arguments and create the correct SQL query from that?
If I understand your question, you could use varargs and change the method signature from
public void postgreSQLInsert(String tblname, String col1, String col2, String col3)
to
public void postgreSQLInsert(String tblname, String... columns)
and then something like
if (insertList == null) {
} else {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(tblname);
sb.append(" (");
for (int i = 0; i < columns.length; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(columns[i]);
}
for (Object[] columnValues : insertList) {
StringBuilder valueSB = new StringBuilder();
for (int i = 0; i < columnValues.length; i++) {
if (i != 0) {
valueSB.append(", ");
}
System.out.println(columnValues[i]);
valueSB.append("'").append(columnValues[i]).append("'");
}
try {
String sql = sb.toString()
+ "VALUES (" + valueSB.toString() + ")";
postgresStmt.executeUpdate(sql);
} catch (PSQLException e) {
System.out.println("Duplicate!");
continue;
}
}

send a broadcast message to all items in list in java

I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.

Categories