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);
}
Related
I am trying to print the plsql variable value (l_console_message) in Java. However, this approach doesn't seem to be working. I belive that something goes wrong at ResultSet bit. I am missing something here. Any idea, what goes wrong?
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("\n" +
" declare " + "\n" +
" p_schema_name varchar2(400):= upper('" + schema + "'); " + "\n" +
" p_temp_table_name varchar2(400) := upper('temp_table_jobs_name'); " + "\n" +
" l_result varchar2(400); " + "\n" +
" l_owner varchar2(200); " + "\n" +
" l_job_name varchar2(200); " + "\n" +
" l_enabled varchar2(200); " + "\n" +
" l_console_message varchar2(4000); " + "\n" +
" cursor c1_temp_table_name is " + "\n" +
" select " + "\n" +
" table_name " + "\n" +
" from all_tables " + "\n" +
" where table_name = p_temp_table_name; " + "\n" +
" begin " + "\n" +
" open c1_temp_table_name; " + "\n" +
" fetch c1_temp_table_name into l_result; " + "\n" +
" if c1_temp_table_name %notfound then " + "\n" +
" execute immediate ' " + "\n" +
" create table '||p_schema_name||'.'||p_temp_table_name||' ( " + "\n" +
" schema_name varchar2 (1000), " + "\n" +
" job_name varchar2(1000), " + "\n" +
" status varchar2(100) " + "\n" +
" )'; " + "\n" +
" l_console_message := p_temp_table_name||' created.'; " + "\n" +
" dbms_output.put_line (l_console_message); " + "\n" +
" end if; " + "\n" +
" close c1_temp_table_name; " + "\n" +
" exception when others then " + "\n" +
" null; " + "\n" +
" end;");
ResultSet rs = statement.execute();
while (rs.next()){
System.out.println(rs.getString(l_console_message));
}
}
catch (SQLException e) {
System.out.println("ERROR: Unable to run SQL statements for schema " + schema + " in beforeMigrate: " + e.getMessage());
}
finally {
if (null != statement) {
try {
statement.close();
}
catch (SQLException se) {
System.out.println("ERROR: Unable to close statement in beforeMigrate: " + se.getMessage());
}
}
}
Thanks in advance :-)
The question linked to from a comment shows an example of what you need to do, but you seem to be struggling to translate that to your situation.
Your anonymous block doesn't (and can't) return a result set, so it shouldn't be executed as a query, and shouldn't be a prepared statement; you need to have a callable statement instead:
CallableStatement statement = null;
try {
statement = connection.prepareStatement("\n" +
...
Then you either need to assign the value of your PL/SQL variable to a bind variable placeholder:
...
" l_console_message := p_temp_table_name||' created.'; " + "\n" +
" ? := l_console_message; " + "\n" +
" end if; " + "\n" +
...
or don't have l_console_message at all (so it doesn't even need to be declared), just assign the string directly to a bind variable placeholder:
...
" ? := p_temp_table_name||' created.'; " + "\n" +
" end if; " + "\n" +
...
Either way the dbms_output call isn't useful here. (It is actually possibly you retrieve the dbms_output buffer from Java, but it's a lot more work).
Then you need to declare an OUT bind variable to receive the string, and call the statement with execute() rather than executeQuery():
statement.registerOutParameter(1, Types.VARCHAR);
statement.execute();
Then you can retrieve the string value that has been put in to the bind variable; e.g. to print it straight to console:
System.out.println(statement.getString(1));
The ResultSet, rs and loop have gone completely.
Your example has following issues:
Anonymous PL/SQL block can return nothing.
Variables declared in a PL/SQL block can't escape the scope. In your example l_console_message variable is visible only in the anonymous PL/SQL block, not in your Java code.
If you want to return a value (or a result set) from a PL/SQL code then you need a stand-alone or package subprogram. Or use the idea linked by #mario-tank where your host environment (your Java code) binds output variables.
Internet and StackOverflow have plenty of examples how to call PL/SQL code from Java.
Here is my queries split up that work perfectly fine...
String sqlstatement = "SELECT WBLinkWebsiteID, WBLinkCategoryParentID, WBLinkTitle, WBLinkURL FROM WEBSITECATEGORY_TABLE WHERE WBLinkCategoryID = ?";
String[] args = { CategorySubID };
Part 2
sqlstatement = "SELECT LOCATIONS_TABLE.LocationWebsiteID, "
+ "LOCATIONS_TABLE.locationCity, "
+ "LOCATIONS_TABLE.locationState, "
+ "LOCATIONS_TABLE.locationCountry, LOCATIONS_TABLE.locationType, "
+ "LOCATIONS_TABLE.locationUrl, "
+ "PREF_TABLE.Pref_SavedTitle "
+ "FROM PREF_TABLE INNER JOIN "
+ "LOCATIONS_TABLE ON PREF_TABLE.Pref_LocationID = LOCATIONS_TABLE.LocationID "
+ "WHERE "
+ "PREF_TABLE.Pref_SavedTitle = '" + theSavedPref + "' ORDER BY LOCATIONS_TABLE.locationState, LOCATIONS_TABLE.locationCity";
Now here is my attempt to combine the two instead of just having 2 go in row back to back and burn time/resources...
String NewSqlstatement = "SELECT LOCATIONS_TABLE.LocationWebsiteID, "
+ "LOCATIONS_TABLE.locationCity, "
+ "LOCATIONS_TABLE.locationState, "
+ "LOCATIONS_TABLE.locationCountry, "
+ "LOCATIONS_TABLE.locationUrl, "
+ "LOCATIONS_TABLE.LocationID, "
+ "PREF_TABLE.Pref_SavedTitle, "
+ "WEBSITECATEGORY_TABLE.WBLinkTitle, "
+ "WEBSITECATEGORY_TABLE.WBLinkURL "
+ "FROM PREF_TABLE INNER JOIN "
+ "LOCATIONS_TABLE ON PREF_TABLE.Pref_LocationID = LOCATIONS_TABLE.LocationID "
+ "INNER JOIN WEBSITECATEGORY_TABLE "
+ "ON WEBSITECATEGORY_TABLE.WBLinkWebsiteID = PREF_TABLE.Pref_WebsiteID "
+ "WHERE "
+ "PREF_TABLE.Pref_SavedTitle = '" + theSavedPref + "'";
Now when I try to do my "SINGLE" way it keeps returning the WHOLE database of Locations in the LOCATIONS_TABLE query. It doesn't do just the exact ones I need.
I know the query works, because I have tested it here: http://sqlfiddle.com/#!6/ede97/2
Now I know my example on sqlfiddle is using MS Server 2014, but I assumed the syntax should be pretty much the same since its just standard SELECT with inner joins, but I could be wrong?
Anyone know what I'm doing wrong? Any help is greatly appreciated
EDIT - Fixed the SQLFIDDLE, I put the wrong statement in the example
Aren't you missing your filter on WBLinkCategoryID in the combined query. Shouldn't you have this:
...
+ "INNER JOIN WEBSITECATEGORY_TABLE "
+ "ON WEBSITECATEGORY_TABLE.WBLinkWebsiteID = PREF_TABLE.Pref_WebsiteID "
+ "WHERE "
+ "WEBSITECATEGORY_TABLE.WBLinkCategoryID IN (<value1>,...,<valueN>) AND "
+ "PREF_TABLE.Pref_SavedTitle = '" + theSavedPref + "'";
So I've got this problem which is really annoying me. I override the onCreate method of my class extending SQLiteOpenHelper:
#Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
final String createAccTableCmd = ("CREATE TABLE IF NOT EXISTS " + ACCOUNTS_TABLE_NAME + " ( " +
ACCOUNT_KEY_ID + " INTEGER PRIMARY KEY ASC AUTOINCREMENT, " +
ACCOUNT_KEY_NAME + " TEXT UNIQUE ON CONFLICT IGNORE NOT NULL ON CONFLICT IGNORE, " +
ACCOUNT_KEY_SELECTED + " INTEGER NOT NULL ON CONFLICT IGNORE, " + //THIS IS IN MILLISECONDS
"CHECK (" + ACCOUNT_KEY_SELECTED + " = 0 OR " + ACCOUNT_KEY_SELECTED + " = 1) ON CONFLICT IGNORE" +
" ) ");
final String oneAndOnlyOneSelectedAccInsertTriggerCmd = "CREATE TRIGGER " + ONE_AND_ONLY_ONE_SELECTED_TRIGGER_INSERT_NAME + " " +
"AFTER INSERT ON " + ACCOUNTS_TABLE_NAME + " " +
"FOR EACH ROW " +
"BEGIN " +
"DELETE FROM " + ACCOUNTS_TABLE_NAME + " WHERE " + ACCOUNT_KEY_ID + " = NEW." + ACCOUNT_KEY_ID + "; " +
"END";
final String oneAndOnlyOneSelectedUpdateTriggerCmd = "CREATE TRIGGER " + ONE_AND_ONLY_ONE_SELECTED_TRIGGER_UPDATE_NAME + " " +
"AFTER UPDATE ON " + ACCOUNTS_TABLE_NAME + " " +
"FOR EACH ROW " +
"WHEN (SELECT(SUM(" + ACCOUNT_KEY_ID + ")) <> 1) " +
"BEGIN " +
"UPDATE " + ACCOUNTS_TABLE_NAME + " SET " + ACCOUNT_KEY_SELECTED + " = 0; " +
"UPDATE " + ACCOUNTS_TABLE_NAME + " SET " + ACCOUNT_KEY_SELECTED + " = 1 WHERE " + ACCOUNT_KEY_ID + " = NEW." + ACCOUNT_KEY_ID + "; " +
"END";
synchronized (DB_LOCK) {
db.beginTransaction();
db.execSQL(createAccTableCmd);
db.execSQL(oneAndOnlyOneSelectedAccInsertTriggerCmd);
db.execSQL(oneAndOnlyOneSelectedUpdateTriggerCmd);
addTableName(ACCOUNTS_TABLE_NAME);
ContentValues cv = new ContentValues();
cv.put(ACCOUNT_KEY_ID, 0);
cv.put(ACCOUNT_KEY_NAME, "name");
cv.put(ACCOUNT_KEY_SELECTED, 0);
Log.d("debug", "-1 if error on insert: " + db.insert(ACCOUNTS_TABLE_NAME, "", cv));
Log.d("debug", "Size: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());
db.setTransactionSuccessful();
db.endTransaction();
LBackupAgent.requestBackup(mContext);
}
Log.d("debug", "Size after ending the transaction: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());
}
One would expect the output of this to be:
-1 if error on insert: 0
Size: 0 /* or 1, if the select takes into account the data not committed of the current transaction, I'm not sure about this */
Size after ending the transaction: 1
When the actual output happens to be:
-1 if error on insert: 0
Size: 0
Size after ending the transaction: 0
How can it be that the insertion is successful but the selection returns 0 rows?
I've checked with a shell that the table does exist, but effectively it is empty, which could be explained by the fact that the tables do not seem to be really existing until onCreate() finishes, justifying as well the 0 returned by the insertion command. Should I guess that this some kind of design constraint to make sure that onCreate does only include CREATE TABLE, CREATE TRIGGER and such type of statements? What if I consider that my schema definition needs an insertion (as is the case)?
Try inserting some dummy values instead of below:
ContentValues defaultAcc = mapAccountToStorable(defaultAccDataModel = new AccountListRecyclerAdapter.AccountDataModel(
LBudgetUtils.getInt(mContext, "default_account_id"),
LBudgetUtils
.getString(mContext, "default_account_name"),
mContext.getResources().getBoolean(
R.bool.default_account_selected)));
Instead of sending nullColumnHack as null send it as "". It will make sure that a row will be created in table even if values are null.
db.insert(ACCOUNTS_TABLE_NAME, "", defaultAcc)
Try below:
db.beginTransaction();
db.execSQL(createAccTableCmd);
db.execSQL(oneAndOnlyOneSelectedAccInsertTriggerCmd);
db.execSQL(oneAndOnlyOneSelectedUpdateTriggerCmd);
db.setTransactionSuccessful();
db.endTransaction();
db.beginTransaction();
addTableName(ACCOUNTS_TABLE_NAME);
AccountListRecyclerAdapter.AccountDataModel defaultAccDataModel;
ContentValues defaultAcc = mapAccountToStorable(defaultAccDataModel = new AccountListRecyclerAdapter.AccountDataModel(LBudgetUtils.getInt(mContext, "default_account_id"), LBudgetUtils.getString(mContext, "default_account_name"), mContext.getResources().getBoolean(R.bool.default_account_selected)));
Log.d("debug", "-1 if error on insert: " + db.insert(ACCOUNTS_TABLE_NAME, null, defaultAcc));
db.setTransactionSuccessful();
db.endTransaction();
Log.d("debug", "Size: " + db.query(ACCOUNTS_TABLE_NAME, null, null, null, null, null, ACCOUNT_KEY_ID + " ASC").getCount());
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.
Lets assume, that we have some 2 tables in SQLite: TBL_PRODUCT and TBL_PRODUCT_ALIASES. Now, I want to query some data from joined two tables:
String sql = "SELECT " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + ", " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" FROM " + TBL_PRODUCT + " LEFT JOIN " + TBL_PRODUCT_ALIASES + " ON " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + " = " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" WHERE " + C_PROD_SERVER_ID + " = ? LIMIT 1";
Cursor cursor = SQLiteDataHelper.getInstance().rawQuery(sql, new String[] {"" + js_CartProduct.getLong("prod_id")});
Thats works great without any problem. And then I want to acquire some data from the returned cursor:
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long prodId = cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID));
//... Some other code
}
Now, here is the problem: C_PROD_PKEY_ID and C_PROD_ALIASES_PKEY_ID are in the real world the same Strings: "_id". And as the result getLong() returns long not from the needed column of cursor.
How should I correctly address to the needed column? Are there other methods besides using AS in sql query OR/AND using definite numbers in cursor.getLong(0) instead of cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID))?
Update:
cursor.getColumnNames() returns this: [_id, _id].