how to improve the interaction between two Hash Map in java? - java

In the below code I am fetching the objects from the hive and passing the tbl_guid to fetch the matches in Mysql and Map will be returned as contains Map<tbl_guid ,uniqueseq>, then the on the based of tbl_guid as key already present the map dRListMap value List<DeletedRecord> DeletedRecord object property tbl_guid will be updated with fetched the uniqueseq fetched from the mysql.
Why am I replacing the tbl_guid with uniqueSeq fetching from the mysql because the on the based with small no corresponding to every tbl_guid which will stored in the HBase later of this, that part of code is not required herein discussion so I haven't posted? I would like to know where is enhancement is required current code.
1st Method
String sql = String.format("select * from %s .HiveTable limit 12", dbName);
Map<String, List<DeletedRecord>> dRListMap = new HashMap<>();
try (Statement stmt = hiveConnection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
int i=0;
while ((rs.next())) {
DeletedRecord delRecord = new DeletedRecord(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4), rs.getDate(5));
String key = rs.getString(2);
List<DeletedRecord> recordList = dRListMap.get(key) == null ? new ArrayList<>() : dRListMap.get(key);
recordList.add(delRecord);
dRListMap.put(key, recordList);
i++;
if (i == 10) {
CommonService.fetchUniquForTblGuid(dRListMap);
i=0;
}
}if(i>0) {
CommonService.fetchUniquForTblGuid(dRListMap);
}
} catch (Exception ee) {
LOGGER.error("Exception occurred while fetching the records from table_name", ee);
}
2nd Method
public static void fetchUniquForTblGuid(Map<String, List<DeletedRecord>> dRListMap) {
List<List<DeletedRecord>> valueList = Collections.list(Collections.enumeration(dRListMap.values()));
List<String> values = valueList.stream().flatMap(Collection::stream).map(DeletedRecord::getTblGuid)
.collect(Collectors.toCollection(ArrayList::new));
Map<String, String> tblSeqMap = getTheUniqueNoForGuids(values);
System.out.println(dRListMap);
for (Map.Entry<String, String> map : tblSeqMap.entrySet()) {
if (dRListMap.containsKey(map.getKey())) {
dRListMap.get(map.getKey()).forEach((DeletedRecord del)->del.setTblGuid(map.getValue()));
}
}
System.out.println(dRListMap);
dRListMap.clear();
}
3rd Method
public static Map<String, String> getTheUniqueNoForGuids(List<String> tableGuids) {
Map<String, String> guidVsUnique = new HashMap<>();
String tableGuidStr = listToCommaDelimitedString(tableGuids);
String fetchthequniforguid = "select distinct tbl_guid,unique_sequ from " + sqlProp.getProperty("database")
+ ".mysql table where tbl_guid in (" + tableGuidStr + ")";
try (PreparedStatement prep = mysqlConnection.prepareStatement(fetchthequniforguid);
ResultSet res = prep.executeQuery()) {
LOGGER.info(String.format("Mysql query %s ", fetchthequniforguid));
while (res.next()) {
guidVsUnique.put(res.getString(1), res.getString(2));
}
} catch (SQLException e) {
LOGGER.info(String.format("Error while executing %s in mysql and occurred %s ", fetchthequniforguid, e));
}
return guidVsUnique;
}
4th Method
public static String listToCommaDelimitedString(List<String> requestIds) {
StringBuffer buffer = new StringBuffer();
if (requestIds.size() == 1)
buffer.append("'" + requestIds.get(0) + "'");
else if (requestIds.size() > 1) {
buffer.append("'");
for (int i = 0; i < requestIds.size(); i++) {
if (i == requestIds.size() - 1)
buffer.append(requestIds.get(i) + "'");
else
buffer.append(requestIds.get(i) + "', '");
}
}
return buffer.toString();
}

Related

error insert data in java netbeans and mysql

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}
For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}
I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

Looking for the optimization of the below code

I have found below code buggy as it degrades the performance of extjs3 grid, i am looking for possibilities of optimization at query or code level, as per my analysis, if we extract out the query there are two nested inner queries which are responding slow, in addition, the code inside while loop trying to find the unique id, can't we have distinct in query, or joins rather than inner queries.
Please suggest me the best practice to follow in order to achieve optimization.
public boolean isSCACreditOverviewGridVisible(String sessionId) {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
boolean result = false;
try {
CommonUtility commUtil = new CommonUtility();
List<String> hmIds = new ArrayList<String>();
Map<String, String> tmStockMap = new TreeMap<String, String>();
Set<String> setRecentCertificate = new HashSet<String>();
String managerAccountId = sessionInfo.getMembershipAccount();
String stockQuery = " select memberId , RootCertficateId from stockposition sp where sp.stocktype = 'TR' and sp.memberId "
+ " IN ( select hm2.accountId from "
DATALINK
+ ".holdingmembers hm2 "
+ " where hm2.holdingId = ( select holdingId from "
DATALINK
+ ".holdingmembers hm1 where hm1.accountId = ? )) "
+ " order by sp.createdDate desc ";
conn = getChildDBConnection();
if (null != conn) {
ps = conn.prepareStatement(stockQuery);
ps.setString(1, managerAccountId);
rs = ps.executeQuery();
if (null != rs) {
while (rs.next()) {
String memberId = rs.getString("memberId");
String rootCertficateId = rs
.getString("RootCertficateId");
if (tmStockMap.containsKey(rootCertficateId)) {
continue;
}
hmIds.add(memberId);
tmStockMap.put(rootCertficateId, memberId);
}
}
rs.close();
ps.close();
if (null != hmIds && !hmIds.isEmpty()) {
String inIds = commUtil.getInStateParam(hmIds);
String mostRecentLicense = "Select RootCertificateId , memberaccountid from "
+ OctopusSchema.octopusSchema
+ ".certificate c where c.memberaccountid IN ("
+ inIds
+ ") and c.isrootcertificate=0 and c.certificationstatusid > 1 order by c.modifieddate desc";
ps = conn.prepareStatement(mostRecentLicense);
rs = ps.executeQuery();
if (null != rs) {
while (rs.next()) {
String rootCertficateId = rs
.getString("RootCertificateId");
String memberaccountid = rs
.getString("memberaccountid");
if (setRecentCertificate.contains(memberaccountid)) {
continue;
}
setRecentCertificate.add(memberaccountid);
if (tmStockMap.containsKey(rootCertficateId)) {
result = true;
break;
}
}
}
rs.close();
ps.close();
} else {
result = false;
}
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
closeDBReferences(conn, ps, null, rs);
}
return result;
}
QUERY:
select RootCertficateId,memberId from stockposition sp where sp.stocktype = 'TR' and sp.memberId
IN ( select hm2.accountId from
DATALINK.holdingmembers hm2
where hm2.holdingId = ( select holdingId from
DATALINK.holdingmembers hm1 where hm1.accountId = '4937' ))
order by sp.createdDate DESC;
One quick approach would be a substition of your IN by EXISTS. If your inner queryes return a lot of rows, it would be a lot more efficient. It depends if your subquery returns a lot of results.
SQL Server IN vs. EXISTS Performance

Migrating a Big Derby embebed database to HSQLDB throw java.lang.OutOfMemoryError: Java heap space

I'm trying to migrate a big db from derby to HSQLDB in a Spring Boot service, like 1.5M regs in few tables of 10 columns. I'm checking with VisualVM; byte and char consume a lot of memory. But the biggest delta in time are in the derby classes.
Sometimes the error is thrown here, but other times thrown in other controllers. I don't want to touch all files to add my catchOutofMemory to restart.
Following is a version of my code, the block comment shows the resume of the process:
run(){//thread inside static function.
while(keepMigrating){
keepMigrating=Migrate();
}
}
private static boolean Migrate(JdbcTemplate derby,JdbcTemplate hsql){
int regs = 100000;
PreparedStatement statement = null;
ResultSet rs = null;
PreparedStatement statementHSQL = null;
try {
for (String table : tables) {//tables contains all tables to migrate
//check how many registers left asd asign to cant, if cant is 0 the empty is true.
PreparedStatement statementUpd[];
while (!empty) {
if (trys <= 0) throw new Exception("redo");
//check how many registers left asd asign to cant, if cant is 0 the empty is true and out of bucle and ready to check next table
/*
*Next process resume as:
*fetch data from derby that hasnt been migrated limited by cant
*create a batch to insert in hsql
*create a update for derby
*create a delete in case someting goes wrong
*excecute insert and update, if someting in batch fail delete the entry in migrate table
*reduce regs to get out of migrate method at some ponint.
*/
statement = derby.getDataSource().getConnection().prepareStatement(
MessageFormat.format(select_all_migrate_false_and_fetch_cant,table));
statementUpd = new PreparedStatement[cant];
ArrayList<String> deleteIds = new ArrayList<>();
StringBuilder columnNames = new StringBuilder();
StringBuilder updateSQL = new StringBuilder();
StringBuilder bindVariables = new StringBuilder();
try {
ResultSetMetaData meta = rs.getMetaData();
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (!meta.getColumnName(i).equals("MIGRATED")) {
if (i > 1) {
columnNames.append(", ");
bindVariables.append(", ");
}
columnNames.append(meta.getColumnName(i));
bindVariables.append('?');
}
}
String sql = "INSERT INTO " + table.substring(4) + " ("
+ columnNames
+ ") VALUES ("
+ bindVariables
+ ")";
statementHSQL = hsql.getDataSource().getConnection().prepareStatement(sql);
HashMap<String, Object> data = new HashMap<>();
int row = 0;
int lastId = 0;
String columnName;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
columnName = meta.getColumnName(i);
Object o = rs.getObject(i);
statementHSQL.setObject(i, o);
if (columnName.equals(mainColumn))
deleteIds.add(String.valueOf(o));
if (!(meta.getColumnType(i) == 2004)) data.put(columnName, o);
if (columnName.equals(mainColumn)) id = rs.getObject(i);
}
int c = 1;
String update = MessageFormat.format("INSERT INTO {0}M ({1}M, MIGRATED) VALUES(?, TRUE)",
table.substring(4), mainColumn).replace("\"M", "M\"");//migrated state is saved in other table
lastId = Integer.valueOf(String.valueOf(id));
statementUpd[row] = derby.getDataSource().getConnection().prepareStatement(update);
statementUpd[row].setObject(1, rs.getObject(mainColumn));
updateSQL = new StringBuilder();
statementHSQL.addBatch();
row += 1;
}
/*
* Build delete query in case of inserted values in HSQLDB but not updated in DERBY
*/
StringBuilder builder = new StringBuilder();
builder.append("(");
int count = 1;
for (String s : deleteIds) {
if (count > 1) builder.append(", ");
builder.append("?");
count++;
}
builder.append(")");
String str = builder.toString();
String queryDelete = "DELETE FROM " + table.substring(4) + " WHERE " + mainColumn + " IN " + str;
PreparedStatement statementHSQLDel = hsql.getDataSource().getConnection().prepareStatement
(queryDelete);
int c = 1;
for (String s : deleteIds) {
statementHSQLDel.setObject(c, s);
c++;
}
boolean deletes = statementHSQLDel.execute();
statementHSQLDel.close();
try {
DatabaseUtils.close(statementHSQLDel);
} catch (Exception e) {
catchOutOfMemory(e);
}
int[] result = statementHSQL.executeBatch();
StringBuilder resultS = new StringBuilder();
int stCounter = 0;
int stCounterInsert = 0;
int stCounterUpdate = 0;
String notarydebug;
for (int i : result) {
int upd = 0;
try {
if (i == 1) upd = statementUpd[stCounter].executeUpdate();
} catch (Exception e) {
catchOutOfMemory(e);
}
stCounterInsert += i;
stCounterUpdate += upd;
resultS.append(",").append(String.valueOf(i)).append("-").append(String.valueOf(upd));
stCounter += 1;
}
statementHSQL.clearBatch();
try {
DatabaseUtils.close(statementHSQL);
} catch (Exception e) {
catchOutOfMemory(e);
}
} catch (SQLException se) {
catchOutOfMemory(se);//otherstuff
} catch (Exception e) {
catchOutOfMemory(e);
}
try {
DatabaseUtils.close(rs);
DatabaseUtils.close(statement);
} catch (Exception e) {
catchOutOfMemory(e);
}
regs=regs-cant;
}
}
}catch (Exception e) {
if (e.getMessage().equals("redo")) return true;//end the loop of regs maximun and get out of method.
}
return false;//end migration succesfully
}
private static int catchOutOfMemory(Throwable e) {
if (e == null) return 0;
if (e instanceof OutOfMemoryError) {
Application.restartBat();
return 1;
} else {
return catchOutOfMemory(e.getCause());
}
}
edit:
So I change as sugested inthe comment to accept a commit, something like this:
Connection hsqlCon;
PrepareStatement hsqlStm;
hsqlCon = JdbcHSQLDB.getDataSource().getConnection();
hsqlStm = hsqlCon.prepareStatement(sql);
hsqlStm.addBatch();
hsqlStm.execute();
hsqlStm.close();
hsqlCon.close();
but i got the same heap memory consumpsion:
The type of table in HSQLDB is not clear from the supplied code. You must use this statement once for each table, to make sure the table data is stored in the finename.data file:
SET TABLE tableName TYPE CACHED
The reported sequence of batch INSERT is not correct. Use this sequence:
Connection hsqlCon;
PrepareStatement hsqlStm;
hsqlCon = JdbcHSQLDB.getDataSource().getConnection();
hsqlStm = hsqlCon.prepareStatement(sql);
{ // repeat this block until all is finished
{ // repeat for 1000 rows
hsqlStm.addBatch();
}
hsqlStm.executeBatch(); // after every 1000 rows
}
hsqlStm.close();
hsqlCon.close();

Exporting data to PDF JAVA, Eclipse, Jasper

I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...

How to pass multiple parameters to a PreparedStatement in java?

I am using the below code to retrive the order data from db2 and it works fine when i am passing only the BranchNumber and used the getWildcards() function since sometime i am passing multiple branch numbers .
public List<Order> getallorders(List<Branch> BranchNumber) throws SQLException {
List<Order> orders = new ArrayList<Order>();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ORDER_NUMBER as ordernumber,SERVICE_TYPE as service"
+ "FROM ORDER WHERE "
+ "BRANCH IN(");
sb.append(getWildCards(BranchNumber.size())).append(")").append(" WITH UR");
String query = sb.toString();
PreparedStatement statement = connection.prepareStatement(query);
for(int i=0 ; i<BranchNumber.size() ;i++)
{
statement.setInt(i+1,BranchNumber.get(i).getBranch());
}
ResultSet resultSet = statement.executeQuery();
{
while (resultSet .next()) {
Order order1 = new Order();
order1.setOrdernumber(resultSet.getInt("ordernumber"));
orders.add(order1);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
return orders;
}
private String getWildCards(int size) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
for(int i =0 ; i<size ; i++)
{
sb = (i == 0) ? sb.append("?")
: sb.append(",").append("?");
}
return sb.toString();
}
Now i need to pass the startDate and endDate inside the function to retrieve the data but the preparedstatement is not formatting the select query with the passed value .
public List<Order> getallorders(List<Branch> BranchNumber,String startDate,String endDate) throws SQLException {
List<Order> orders = new ArrayList<Order>();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ORDER_NUMBER as ordernumber,SERVICE as service"
+ "FROM ORDER WHERE "
+ "BRANCH IN(");
sb.append(getWildCards(BranchNumber.size())).append(")");
sb.append("AND ORDERDATE BETWEEN ? and ? WITH UR");
String query = sb.toString();
PreparedStatement statement =
connection.prepareStatement(query);
for(int i=0 ; i<BranchNumber.size() ;i++)
{
statement.setInt(i+1,BranchNumber.get(i).getBranch());
}
ResultSet resultSet = statement.executeQuery();
{
while (resultSet .next()) {
Order order1 = new Order();
order1.setOrdernumber(resultSet.getInt("ordernumber"));
orders.add(order1);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
return orders;
}
Can someone please explain me what i am doing wrong here and how i can get the expected preparedstatement,below is the formatted query coming in my log and error message recorded,
SELECT ORDER_NUMBER as ordernumber,SERVICE_TYPE as service FROM .ORDER WHERE
BRANCH_NUMBER IN(?) + AND ORDERDATE BETWEEN ? AND ? WITH UR
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104,
SQLSTATE=42601, SQLERRMC=ORDER DATE BETWEEN ? AND;H_NUMBER IN(?) + AND;
<order_siblings_by>, DRIVER=3.63.75
at com.ibm.db2.jcc.am.fd.a(fd.java:679)
Each ? in the PrepareStatement should be assigned a value. Here is an example adopted from here :
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
PreparedStatement updateSales = con.prepareStatement(updateString);
updateSales.setInt(1, 500); //set value to first `?`
updateSales.setString(2, "roasted"); //set value to second `?`

Categories

Resources