This code serves to update a customer's data in sql. How I can simplify this code? Is there another way to do this?
if (!clienteOld.getNome().equalsIgnoreCase(clienteNew.getNome())) {
stmt.executeUpdate("UPDATE CLIENTES SET NOME = '" + clienteNew.getNome() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- NOME=" + clienteNew.getNome());
}
if (!clienteOld.getDataNascimento().equalsIgnoreCase(clienteNew.getDataNascimento())) {
stmt.executeUpdate("UPDATE CLIENTES SET DATA_NASCI = '" + clienteNew.getDataNascimento() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- DATA NASCIMENTO=" + clienteNew.getDataNascimento());
}
if (!clienteOld.getMorada().equalsIgnoreCase(clienteNew.getMorada())) {
stmt.executeUpdate("UPDATE CLIENTES SET MORADA = '" + clienteNew.getMorada() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- MORADA=" + clienteNew.getMorada());
}
if (!clienteOld.getPais().equalsIgnoreCase(clienteNew.getPais())) {
stmt.executeUpdate("UPDATE CLIENTES SET PAIS = '" + clienteNew.getPais() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- PAIS=" + clienteNew.getPais());
}
if (!clienteOld.getNacionalidade().equalsIgnoreCase(clienteNew.getNacionalidade())) {
stmt.executeUpdate("UPDATE CLIENTES SET NACIONALIDADE = '" + clienteNew.getNacionalidade() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- NACIONALIDADE=" + clienteNew.getNacionalidade());
}
if (!clienteOld.getBI().equalsIgnoreCase(clienteNew.getBI())) {
stmt.executeUpdate("UPDATE CLIENTES SET BI = '" + clienteNew.getBI() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- BI=" + clienteNew.getBI());
}
if (!clienteOld.getTipoIndentificaçao().equalsIgnoreCase(clienteNew.getTipoIndentificaçao())) {
stmt.executeUpdate("UPDATE CLIENTES SET TIPO_IDENT = '" + clienteNew.getTipoIndentificaçao() + "' WHERE ID = " + id1 + ";");
criarLog("Ficha do cliente: " + clienteOld.getNome() + " foi atualizada -- TIPO IDENTIFICAÇAO=" + clienteNew.getTipoIndentificaçao());
}
Try this logic:
StringBuilder sql = new StringBuilder("UPDATE CLIENTES SET ");
Map<String, String> cols = new HashMap<>();
if (!clienteOld.getNome().equalsIgnoreCase(clienteNew.getNome())) {
cols.put("NOME", clienteNew.getNome());
}
if (!clienteOld.getDataNascimento().equalsIgnoreCase(clienteNew.getDataNascimento())) {
cols.put("DATA_NASCI", clienteNew.getDataNascimento());
}
// and the other if statements
Then you can iterate the map and build your actual update statement:
int cnt = 0;
for (Map.Entry<Integer, Integer> entry : cols.entrySet()) {
if (cnt > 0) sql.append(", ");
sql.append(entry.getKey()).append(" = '").append(entry.getValue()).append("'");
++cnt;
}
sql.append(" WHERE ID = ").append(id1).append(";");
But note that this approach is not SQL injection safe. If these values are coming from the outside, e.g. a UI, then you should absolutely be using a prepared statement. There is nothing inherently wrong with using a separate statement for each if condition. I only answered to show that you can cleanup your current approach, should it be appropriate.
if (!oldClient.getName().equalsIgnoreCase(newClient.getName())) {
stmt.executeUpdate("UPDATE CLIENTS SET NAME = '" + newClient.getName() +
"' WHERE ID = " + id1 + ";");
}
if (!oldClient.getBirthDate().equalsIgnoreCase(newClient.getBirthDate())) {
stmt.executeUpdate("UPDATE CLIENTS SET BIRTH = '" + newClient.getBirthDate() +
"' WHERE ID = " + id1 + ";");
}
can be rewritten as
if (!oldClient.getName().equalsIgnoreCase(newClient.getName()) ||
!oldClient.getBirthDate().equalsIgnoreCase(newClient.getBirthDate())) {
stmt.executeUpdate("UPDATE CLIENTS SET NAME = '" + newClient.getName() +
"', BIRTH = '" + newClient.getBirthDate() +
"' WHERE ID = " + id1 + ";");
}
This will perform better because it executes one SQL statement instead of two. The fact that you are possibly setting two columns when only one needs to be set is probably of little consequence, compared with that.
Notes:
If you try to "optimize" the number of columns set, the code is more complicated; see Tim's answer.
This should probably be done with a PreparedStatement and statement parameters to avoid SQL injection. If you follow the above pattern, the changes needed to use a PreparedStatement are straight forward.
First, you can use one query to update every fields :
"UPDATE CLIENTES SET DATA_NASCI "
+ "MORADA = '" + clienteNew.getMorada() + "'"
+ "PAIS = '" + clienteNew.getPais() + "'"
+ "NACIONALIDADE = '" + clienteNew.getNacionalidade() + "'"
+ "BI = '" + clienteNew.getBI() + "'"
+ "TIPO_IDENT = '" + clienteNew.getTipoIndentificaçao() + "'"
+ "WHERE ID = " + id1 + ";"
Please use a PreparedStatement instead of this, this would be much safer !
All you have to do is check if only one field have changed (to prevent the transaction doing nothing) using a condition check each field :
if (!clienteOld.getNome().equalsIgnoreCase(clienteNew.getNome()))
|| (clienteOld.getDataNascimento().equalsIgnoreCase(clienteNew.getDataNascimento()))
|| (!clienteOld.getMorada().equalsIgnoreCase(clienteNew.getMorada()))
|| (!clienteOld.getPais().equalsIgnoreCase(clienteNew.getPais()))
|| (!clienteOld.getNacionalidade().equalsIgnoreCase(clienteNew.getNacionalidade()))
|| (!clienteOld.getBI().equalsIgnoreCase(clienteNew.getBI()))
|| (!clienteOld.getTipoIndentificaçao().equalsIgnoreCase(clienteNew.getTipoIndentificaçao()))
This can be a bit verbose ... so why not reduce this code a bit using Stream and some function references to compare and build a map of value to update :
First, the class Bean for our example :
class Bean {
String firstname, lastname;
public Bean(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
Then, let's create a mapping of Column name and Function, the function will allow us to use the getters of Bean :
Map<String, Function<Bean, String>> functions = new HashMap<>();
functions.put("FIRSTNAME", Bean::getFirstname);
functions.put("LASTNAME", Bean::getLastname);
Then, using final instance (to be used in a Predicate)
final Bean clienteNew = new Bean("Foo", "Bar");
final Bean clienteOld = new Bean("Foo", "Boo");
Map<String, String> values = functions.entrySet()
.stream()
//filter only the value that changed between clienteOld and clienteNew
.filter(entry -> !entry.getValue().apply(clienteOld).equals(entry.getValue().apply(clienteNew)))
//then collect the map `name -> new value`
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().apply(clienteNew)));
System.out.println(values);
{LASTNAME=Bar}
This will give you a Map<String, String> that can be used to create a PreparedStatement with only the column we want/need to edit.
If you have a new field, just need to add the mapping in the functions map and you are good to go. (this become a bit more complex with primitive type...)
Related
I am trying to sort List<Map<String, Object>> from a request to an oracle database. The format I am receiving is this
63: "Preasignación"
401: "Categorización de posiciones RPV"
509: "Genérica"
532: "Baja de conservación de número"
537: "Pooles ADSL RIMA"
660: "Activación"
886: "CENTREX"
905: "Conservación de número"
920: "Suspensión y rehabilitación"
955: "STB, AABB, PBX e ISPBX"
As you can see they are sorted by numbers, but I want to sort them by value "alphabetically". How can I do it? Please try to not freak out with spanish code :) this is inherited code. Here my code.
public ArrayList<String> ObtenerIdsTiposOrdenPorPerfilLdap(String perfiles) {
String query = "";
ArrayList<String> tipos = new ArrayList<String>();
try {
query = " SELECT ID_PARAMETRO FROM PARAMETRO WHERE EXISTS( " +
" SELECT DISTINCT(ID_TIPO_ORDEN) FROM REL_PERF_LDAP_PERF_TP_ORD_SIS " +
" WHERE ID_PERFIL_LDAP IN (" + perfiles + ") " +
" AND ID_TIPO_ORDEN = -1) " +
" AND ID_TIPO_PARAMETRO = " + Parametro.ID_TIPO_PARAMETRO_TIPO_ORDEN +
" UNION " +
" SELECT ID_PARAMETRO FROM PARAMETRO WHERE ID_PARAMETRO IN ( " +
" SELECT DISTINCT(ID_TIPO_ORDEN) FROM REL_PERF_LDAP_PERF_TP_ORD_SIS " +
" WHERE ID_PERFIL_LDAP IN (" + perfiles + ")) " +
" AND ID_TIPO_PARAMETRO = " + Parametro.ID_TIPO_PARAMETRO_TIPO_ORDEN +
" ORDER BY ID_PARAMETRO ";
List<Map<String, Object>> result = jdbcTemplate.queryForList(query);
for (Map<String, Object> map : result) {
tipos.add(String.valueOf(map.get("ID_PARAMETRO")));
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
query = null;
}
return tipos;
}
If the textual descriptions of PARAMETRO ("preasignación", ...) are actually in PARAMETRO itself (let's call that column TXT_PARAMETRO), it should be enough to ask the database to do the ordering: remove
" ORDER BY ID_PARAMETRO ";
and add
" ORDER BY TXT_PARAMETRO ";
instead.
I wrote a piece of JDBC template code, which inserts the record in the table, but the problem is my execution is stuck on this particular snippet, it seems some kind of hang up. I didn't figure out the cause as query properly running in sqldeveloper
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
// the above line find the required data, if data is found then it proceeds
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
You people saw try-catch , my execution stuck inside try and catch and here is the insertion code in my implementation class. when i commented the above code then my application works fine, but why my application stuck here, I am not able to figure it out, kindly help me
#Override
public void save(SalaryDetail details, String tableSuffix) {
String tabName = "SALARY_DETAIL_" + tableSuffix;
// String q = "INSERT INTO " + tabName + "(ID "
String q = "INSERT INTO SALARY_DETAIL_TBL "
+ " (ID "
+ " ,EMP_NAME "
+ " ,EMP_CODE "
+ " ,NET_SALARY "
+ " ,YYYYMM "
+ " ,PAY_CODE "
+ " ,EMP_ID "
+ " ,PAY_CODE_DESC "
+ " ,REMARK "
+ " ,PAY_MODE ) "
+ " (SELECT (sd.SALARY_REPORT_ID) ID "
+ " ,(sd.emp_name) emp_name "
+ " ,(sd.EMP_CODE) EMP_CODE "
+ " ,(sd.amount) NET_SALARY "
+ " ,(sd.YYYYMM) YYYYMM "
+ " ,(sd.pay_code) pay_code "
+ " ,(sd.emp_id) emp_id "
+ " ,(sd.PAY_CODE_DESC) PAY_CODE_DESC "
+ " ,(sd.REMARK) REMARK "
+ " ,(sd.PAY_MODE)PAY_MODE "
// + " FROM SALARY_DETAIL_REPORT_" + tableSuffix + " sd "
+ " FROM SALARY_DETAIL_REPORT_TBL sd "
+ " WHERE sd.PAY_CODE = 999 "
+ " AND sd.EMP_ID IS NOT NULL "
// + " AND sd.EMP_ID NOT IN (SELECT EMP_ID FROM SALARY_DETAIL_" + tableSuffix + ") "
+ " AND sd.EMP_ID NOT IN (SELECT EMP_ID FROM SALARY_DETAIL_TBL) "
+ " ) ";
MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("id", details.getId());
param.addValue("EMP_NAME", details.getEmpName());
param.addValue("EMP_CODE", details.getEmpCode());
param.addValue("NET_SALARY", details.getNetSalary());
param.addValue("GROSS_EARNING", details.getGrossEarning());
param.addValue("GROSS_DEDUCTION", details.getGrossDeduction());
param.addValue("YYYYMM", details.getYyyymm());
param.addValue("EMP_ID", details.getEmployee() != null ? details.getEmployee().getEmpId() : null);
KeyHolder keyHolder = new GeneratedKeyHolder();
getNamedParameterJdbcTemplate().update(q, param);
// details.setId(((BigDecimal) keyHolder.getKeys().get("ID")).longValue());
}
The main problem is in your query is Not In condition. It will degrade your performance. Try to fetch the "SELECT EMP_ID FROM SALARY_DETAIL_TB" in a separate query and pass in the Not in block in the main query. This will increase the performance of your query. Every time a save is performed this will fire the select query every time.
You have to decide whether you will insert records from SELECT or from the application.
If you don't need to manipulate with data after their select then you can simply call one INSERT INTO SELECT statement without any for cycle. It will be fast because of the only one INSERT statement call.
So you will implement method like copyAllInSalaryDetail(tableSuffix, regionId, circleId) in your SalaryDetailReportDAO and that method will execute INSERT INTO salary_detail_tbl... (...) (SELECT ... WHERE ...) using the same WHERE condition as you have in findAll() method. All inserts will be done only on the Database layer.
If you want to manipulate with data before their insert you can continue with your approach using SalaryDetail bean and for cycle, but you should remove the SELECT part from the INSERT statement and use values from the provided bean. Then the save() method can look like:
#Override
public void save(SalaryDetail details, String tableSuffix) {
// use tableSuffix if it is really needed
String q = "INSERT INTO SALARY_DETAIL_TBL "
+ " (ID "
+ " ,EMP_NAME "
+ " ,EMP_CODE "
+ " ,NET_SALARY "
+ " ,YYYYMM "
+ " ,PAY_CODE "
+ " ,EMP_ID "
+ " ,PAY_CODE_DESC "
+ " ,REMARK "
+ " ,PAY_MODE ) "
+ " VALUES (:id "
+ " ,:emp_name "
+ " ,:emp_code "
+ " ,:net_salary "
+ " ,:yyyymm "
+ " ,:pay_code "
+ " ,:emp_id "
+ " ,:pay_code_desc "
+ " ,:remark "
+ " ,:pay_mode)";
MapSqlParameterSource param = new MapSqlParameterSource();
// KeyHolder keyHolder = new GeneratedKeyHolder();
// details.setId(((BigDecimal) keyHolder.getKeys().get("ID")).longValue());
param.addValue("id", details.getId());
param.addValue("emp_name", details.getEmpName());
param.addValue("emp_code", details.getEmpCode());
param.addValue("net_salary", details.getNetSalary());
param.addValue("pay_code", details.getPayCode());
param.addValue("pay_code_desc", details.getPayCodeDesc());
param.addValue("pay_mode", details.getPayMode());
param.addValue("remark", details.getPayRemark());
param.addValue("yyyymm", details.getYyyymm());
param.addValue("emp_id", details.getEmployee() != null ? details.getEmployee().getEmpId() : null);
getNamedParameterJdbcTemplate().update(q, param);
}
I was wondering if someone here could help me, I can't find a solution for my problem and I have tried everything.
What I am trying to do is read and parse lines in a csv file into java objects and I have succeeded in doing that but after it reads all the lines it should insert the lines into the database but it only inserts the 1st line the entire time and I don't no why. When I do a print it shows that it is reading all the lines and placing them in the objects but as soon as I do the insert it wants to insert only the 1st line.
Please see my code below:
public boolean lineReader(File file){
BufferedReader br = null;
String line= "";
String splitBy = ",";
storeList = new ArrayList<StoreFile>();
try {
br = new BufferedReader(new FileReader(file));
while((line = br.readLine())!=null){
line = line.replace('|', ',');
//split on pipe ( | )
String[] array = line.split(splitBy, 14);
//Add values from csv to store object
//Add values from csv to storeF objects
StoreFile StoreF = new StoreFile();
if (array[0].equals("H") || array[0].equals("T")) {
return false;
} else {
StoreF.setRetailID(array[1].replaceAll("/", ""));
StoreF.setChain(array[2].replaceAll("/",""));
StoreF.setStoreID(array[3].replaceAll("/", ""));
StoreF.setStoreName(array[4].replaceAll("/", ""));
StoreF.setAddress1(array[5].replaceAll("/", ""));
StoreF.setAddress2(array[6].replaceAll("/", ""));
StoreF.setAddress3(array[7].replaceAll("/", ""));
StoreF.setProvince(array[8].replaceAll("/", ""));
StoreF.setAddress4(array[9].replaceAll("/", ""));
StoreF.setCountry(array[10].replaceAll("/", ""));
StoreF.setCurrency(array[11].replaceAll("/", ""));
StoreF.setAddress5(array[12].replaceAll("/", ""));
StoreF.setTelNo(array[13].replaceAll("/", ""));
//Add stores to list
storeList.add(StoreF);
}
} //print list stores in file
printStoreList(storeList);
executeStoredPro(storeList);
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured: " + ex.getMessage(), ex);
//copy to error folder
//email
}
return false;
}
public void printStoreList(List<StoreFile> storeListToPrint) {
for(int i = 0; i <storeListToPrint.size();i++){
System.out.println( storeListToPrint.get(i).getRetailID()
+ storeListToPrint.get(i).getChain()
+ storeListToPrint.get(i).getStoreID()
+ storeListToPrint.get(i).getStoreName()
+ storeListToPrint.get(i).getAddress1()
+ storeListToPrint.get(i).getAddress2()
+ storeListToPrint.get(i).getAddress3()
+ storeListToPrint.get(i).getProvince()
+ storeListToPrint.get(i).getAddress4()
+ storeListToPrint.get(i).getCountry()
+ storeListToPrint.get(i).getCurrency()
+ storeListToPrint.get(i).getAddress5()
+ storeListToPrint.get(i).getTelNo());
}
}
public void unzip(String source, String destination) {
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
deleteStoreFile(source);
} catch (ZipException ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error unzipping file : " + ex.getMessage(), ex);
}
}
public void deleteStoreFile(String directory) {
try {
File file = new File(directory);
file.delete();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured when trying to delete file " + directory + " : " + ex.getMessage(), ex);
}
}
public void executeStoredPro(List<StoreFile> storeListToInsert) {
Connection con = null;
CallableStatement st = null;
try {
String connectionURL = MSSQLConnectionURL;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection(connectionURL, MSSQLUsername, MSSQLPassword);
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores WHERE StoreID = " + storeListToInsert.get(i).getStoreID() + " AND RetailID = "+ storeListToInsert.get(i).getRetailID() + ")"
+ " UPDATE tblPay#RetailStores "
+ " SET RetailID = '" + storeListToInsert.get(i).getRetailID() + "',"
+ " StoreID = '" + storeListToInsert.get(i).getStoreID() + "',"
+ " StoreName = '" + storeListToInsert.get(i).getStoreName() + "',"
+ " TestStore = 0,"
+ " Address1 = '" + storeListToInsert.get(i).getAddress1() + "',"
+ " Address2 = '" + storeListToInsert.get(i).getAddress2() + "',"
+ " Address3 = '" + storeListToInsert.get(i).getAddress3() + "',"
+ " Address4 = '" + storeListToInsert.get(i).getAddress4() + "',"
+ " Address5 = '" + storeListToInsert.get(i).getAddress5() + "',"
+ " Province = '" + storeListToInsert.get(i).getProvince() + "',"
+ " TelNo = '" + storeListToInsert.get(i).getTelNo() + "',"
+ " Enabled = 1"
+ " ELSE "
+ " INSERT INTO tblPay#RetailStores ( [RetailID], [StoreID], [StoreName], [TestStore], [Address1], [Address2], [Address3], [Address4], [Address5], [Province], [TelNo] , [Enabled] ) "
+ " VALUES "
+ "('" + storeListToInsert.get(i).getRetailID() + "',"
+ "'" + storeListToInsert.get(i).getStoreID() + "',"
+ "'" + storeListToInsert.get(i).getStoreName() + "',"
+ "0,"
+ "'" + storeListToInsert.get(i).getAddress1() + "',"
+ "'" + storeListToInsert.get(i).getAddress2() + "',"
+ "'" + storeListToInsert.get(i).getAddress3() + "',"
+ "'" + storeListToInsert.get(i).getAddress4() + "',"
+ "'" + storeListToInsert.get(i).getAddress5() + "',"
+ "'" + storeListToInsert.get(i).getProvince() + "',"
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
con.close();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error executing Stored proc with error : " + ex.getMessage(), ex);
nmtbatchservice.NMTBatchService2.mailingQueue.addToQueue(new Mail("support#nmt-it.co.za", "Service Email Error", "An error occurred during Store Import failed with error : " + ex.getMessage()));
}
}
Any advise would be appreciated.
Thanks
Formatting aside, your code is wrong (I truncated the part of the query):
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Don't do a classical for loop while foreach exists and can be better to use, and even if you do a classical for loop, use local variables, eg:
for(int i = 0; i <storeListToInsert.size();i++){
StoreFile item = storeListToInsert.get(i);
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Which could translate as:
for (StoreFile item : storeListToInsert) {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Now, the second problem is your PreparedStatement. A PreparedStatement allow reusing, which means you don't need to create PreparedStatement per item which is what you are doing.
Also, you need to close the statement otherwise, you will exhaust resources..
You must not create it in the for loop, but before, like this:
PreparedStatement st = null;
try {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "SET RetailID = :RetailID ,"
+ "1)");
for (StoreFile item : storeListToInsert) {
st.setString(":RetailID", item.getRetailID());
st.executeUpdate();
}
} finally {
if (null != st) {st.close();}
}
In brief:
You need to close the PreparedStatement after usage, because it is a memory leak otherwise.
You need to rewrite your query using either named parameters, either positional parameter (like: ? or ?1 for first parameter, and so on). I favor named parameters, but they are not always available. The example I linked all use positional parameters.
You need to set the value for each parameters in the for loop, and care about the type. I expected here that getRetailID() is a String, but it might be a Long in that case that would be st.setLong.
Your query is reusable, avoiding the need to reparse it/resend it to the SQL Server. You just send the parameter's values. Beside, you can also batch update.
A PreparedStatement for a statement that you generate (like you are doing) is overkill, and beside, it is missing SQL escapement to protect the String you inject to your query to avoid it being badly interpreted (aka SQL errors) or worst, to do what it was not intended for (like, even if it is far fetched, dropping the whole database, etc).
The executeUpdate() return the number of updated rows. You can check it to see if there was updates.
You can also use Batch statement, which can help performances.
And finally, you can use opencsv to parse common CSV files.
Following code needs modification can we use constants files if yes then how we can segregate string in separate files so that loop continues then performance is not impacted
for (int j = 0; j < subconfigListRLC.size(); j++) {
StringBuffer sqlQuery = new StringBuffer();
test = (SubConfigurationDetailsObject) subconfigListRLC.get(j);
if (test.getFlag().equalsIgnoreCase("T")) {
sqlQuery = sqlQuery.append("update SUB_CONFIG set TSTED = "
+ test.getSubConfigurationIndexNo() + " , Q_SUB_INDX = 0 "
+ "where BASE_ENG_KEY = '" + test.getBaseEngineKey() + "' "
+ "AND MODEL_YEAR = '" + modelYear + "' "
+ "AND RLHP_LVW = '" + test.getRoadLoadHorsepowerValue() + "' "
+ "AND LVW_TEST_WT_WO_CONT = '" + test.getEtwValue() + "' "
+ "AND INERTIA_WT_CLASS = '" + test.getInertiaWeightClassNo() + "' "
+ "AND TEST_GROUP_ID = " + test.getTestGroupId() + " "
+ "AND ENGINE_CODE = '" + test.getEngineCode() + "' "
+ "AND AXLE_RATIO = '" + test.getAxleRatioValue() + "'");
} else if (test.getFlag().equalsIgnoreCase("U")) {
sqlQuery = sqlQuery.append("update SUB_CONFIG set Q_SUB_INDX = "
+ test.getSubConfigurationIndexNo() + " "
+ "where BASE_ENG_KEY = '" + test.getBaseEngineKey() + "' "
+ "AND MODEL_YEAR = '" + modelYear + "' "
+ "AND RLHP_LVW = '" + test.getRoadLoadHorsepowerValue() + "' "
+ "AND LVW_TEST_WT_WO_CONT = '" + test.getEtwValue() + "' "
+ "AND INERTIA_WT_CLASS = '" + test.getInertiaWeightClassNo() + "' "
+ "AND TEST_GROUP_ID = " + test.getTestGroupId() + " "
+ "AND ENGINE_CODE = '" + test.getEngineCode() + "' "
+ "AND AXLE_RATIO = '" + test.getAxleRatioValue() + "'");
}
//System.out.println("Query----------->"+sqlQuery.toString());
processor.getUpdateAccessor().executeUpdateSql(sqlQuery.toString());
}
Use a Java PreparedStatement in order to build the query. You can then store the query string for the PreparedStatement in a properties file. Read the two possible query strings into variables before entering the loop (in fact you may want to build both PreparedStatements before entering the loop - depending on whether you always use them both). You can then call clearParamaters, then set your new parameters, execute, repeat.
As you asked for the exact details, something like this. Search for javadocs on PreparedStatement. Javadocs are always worth reading.
String sql = "update SUB_CONFIG set TSTED = ? , Q_SUB_INDX = ? " +
"where BASE_ENG_KEY = ? " +
"AND MODEL_YEAR = ? " +
"AND RLHP_LVW = ? " +
"AND LVW_TEST_WT_WO_CONT = ? " +
"AND INERTIA_WT_CLASS = ? " +
"AND TEST_GROUP_ID = ? " +
"AND ENGINE_CODE = ? " +
"AND AXLE_RATIO = ?");
PreparedStatement statement = connection.createPreparedStatement(sql);
for (SubConfigurationDetailsObject test: subconfigListRLC) {
if (test.getFlag().equalsIgnoreCase("T")) {
statement.setIntParam(1, test.getSubConfigurationIndexNo());
statement.setIntParam(2, 0);
} else if (test.getFlag().equalsIgnoreCase("U")) {
statement.setIntParam(1, 0);
statement.setIntParam(2, test.getSubConfigurationIndexNo());
} else {
continue;
}
statement.set...Param(3, ...);
...
statement.executeUpdate();
}
You may probably only need one PreparedStatement, and the result is indeed faster.
BTW. better use StringBuilder instead of StringBuffer.
Im trying to update several columns in a row through a dynamic query.
columnnames is an Arraylist containing all the names of the columns for the selected table
Arrays.toString(row) contains the user inputs that the row should be updated to.
Im getting this error message at columnnames when trying to run this: No such column[SNO,SNAME,STATUS,CITY]. I dont know of any way to fix this?
query = "UPDATE " + tablename + " SET '" + columnnames + "' = '" + Arrays.toString(row) + "' WHERE " + FirstColumn + " = '" + rowstandard + "'";
You need to update each column separately. You can't pass them each as arrays.
query = "UPDATE " + tablename + " SET "
foreach(int i=0; i< columnnames.length; i++)
{
query+= "'" + columnnames[i] + "' = '" + row[i] + "',"
}
query = StripLastComma(query) //Not sure how to do this in Java.
query +="' WHERE " + FirstColumn + " = '" + rowstandard + "'"
Thats not going to work as the syntax for set is SET ColumnA = :ValueA, ColumnB = :ValueB WHERE " + FirstColumn + " = '" + rowstandard + "'";
As it was pointed out correct syntax for update query is:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
see Update syntax.
Having said that, I would do something like this (using guava):
StringBuilder query = new StringBuilder();
query.append("UPDATE " + tablename + " SET ");
// build a map of col name/value
Map<String, String> map = Maps.toMap(columnnames, new Function<String, String>(){
#Override
public String apply(String input){
return row[columnnames.indexOf(input)].toString();
}
});
query.append(Joiner.on(",").withKeyValueSeparator("=").join(map));
query.append(" WHERE " + FirstColumn + " = '" + rowstandard + "'");
query.toString();