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());
Related
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);
}
Numerous StackOverflow problems are similar, but it is not an issue of incorrect spacing in the query string. I have two tables, one for peers and one for messages, which has foreign keys associated with ids in the peer table.
Here are my creation strings:
private static final String DATABASE_CREATE = "CREATE TABLE " + PEER_TABLE + " ("
+ PeerContract._ID + " INTEGER PRIMARY KEY, "
+ PeerContract.NAME + " TEXT NOT NULL, "
+ PeerContract.ADDRESS + " TEXT NOT NULL, "
+ PeerContract.PORT + " TEXT NOT NULL);";
private static final String MESSAGE_TABLE_CREATE = "CREATE TABLE " + MESSAGE_TABLE + " ("
+ MessageContract._ID + " INTEGER PRIMARY KEY, "
+ MessageContract.MESSAGE_TEXT + " TEXT NOT NULL, "
+ MessageContract.SENDER + " TEXT NOT NULL, "
+ MessageContract.PEER_FOREIGN_KEY + " INTEGER NOT NULL, "
+ "FOREIGN KEY ("+ MessageContract.PEER_FOREIGN_KEY+") " +
"REFERENCES "+PEER_TABLE+"("+PeerContract._ID+") ON DELETE CASCADE);";
private static final String CREATE_INDEX = "CREATE INDEX " + INDEX + " ON " +
MESSAGE_TABLE + "(" + MessageContract.PEER_FOREIGN_KEY + ");";
I want to query a list of all received messages so I did this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}
Which makes sense to me. And the spacing so far is alright there is no errors.
In my main activity I have a SimpleCursorAdapter:
listView = (ListView) findViewById(R.id.msgList);
dbAdapter = new ServerDbAdapter(this);
dbAdapter.open();
String[] from = new String[] {PeerContract.NAME, MessageContract.MESSAGE_TEXT};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(cursorAdapter);
cursor = dbAdapter.fetchAllMessages();
cursorAdapter.swapCursor(cursor);
I get "column 'name' does not exist" and it is driving me crazy!
I properly defined it in DATABASE_CREATE as PeerContract.NAME. I'm guessing its happening because of fetchAllMessages but I am not sure how to fix it.
You are not selecting the PeerContract.NAME, MessageContract.MESSAGE_TEXT in your fetchAllMessages() method. Change it to this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ PeerContract.NAME + ", "
+ PeerContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}
I have this onCreate method in my SQLiteOpenHelper
class, and I would like to add a unique constraint on these two columns (composite unique columns):
SongContract.SongEntry.COLUMN_TITLE
SongContract.SongEntry.COLUMN_RELEASEDATE
But I am getting an error:
Cannot resolve method UNIQUE
Here is my code:
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER, " +
UNIQUE(SongContract.SongEntry.COLUMN_TITLE, SongContract.SongEntry.COLUMN_RELEASEDATE) +
SongContract.SongEntry.COLUMN_RATING + " TEXT);";
db.execSQL(SQL_CREATE_SONG_TABLE);
}
What is the correct syntax to achieve my goal?
I found the corrrect syntax after playing around sqllite:
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER NOT NULL, " +
SongContract.SongEntry.COLUMN_RATING + " TEXT, " + "UNIQUE" + "(" +
SongContract.SongEntry.COLUMN_TITLE + "," + SongContract.SongEntry.COLUMN_RELEASEDATE + ") " + ");";
I am trying to get all the values in a table that have column _parentbook set to a certain value. When I try to retrieve the entries I get the error shown below.
E/SQLiteLog: (1) table recipes has no column named _parentbook
E/SQLiteDatabase: Error inserting _parentbook=Test _recipemethod=Stir in pot for 20 mins _recipeingredients=No bugs, freedom _recipedescription=Test recipe _recipename=Recipe 1 in Test _recipenotes=Do on Android Studio
The error refers to the method below that I use to add a recipe to the database
public void addRecipe(Recipe recipe) {
ContentValues values = new ContentValues();
values.put(COLUMN_RECIPE_NAME, recipe.getRecipeTitle());
values.put(COLUMN_RECIPE_DESCRIPTION, recipe.getRecipeDescription());
values.put(COLUMN_RECIPE_INGREDIENTS, recipe.getIngredients());
values.put(COLUMN_RECIPE_METHOD, recipe.getMethod());
values.put(COLUMN_RECIPE_NOTES, recipe.getNotes());
//values.put(COLUMN_IMAGE_ID, recipe.getImageId());
values.put(COLUMN_PARENT_BOOK, recipe.getParentBook());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECIPES, null, values);
db.close();
}
Code used to initialise TABLE_RECIPES:
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "OnCreate() called");
db.execSQL(CREATE_TABLE_RECIPES);
}
Method for getting the recipes from the table:
List<Recipe> recipes;
public List<Recipe> getRecipes(String bookName) {
recipes = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
//String query = "SELECT "+ COLUMN_PARENT_BOOK +" FROM " + TABLE_RECIPES + " WHERE " + COLUMN_PARENT_BOOK + "=" + bookName;
String query = "SELECT * FROM " + TABLE_RECIPES;// + " WHERE 1";
// Cursor going to point to a location in the results
Cursor c = db.rawQuery(query, null);
// Move it to the first row of your results
c.moveToFirst();
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)) != null) {
recipes.add(new Recipe(
c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_DESCRIPTION)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_INGREDIENTS)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_METHOD)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_NOTES)),
// Add image here if required
c.getString(c.getColumnIndex(COLUMN_PARENT_BOOK))
));
}
} while (c.moveToNext());
}
db.close();
//c.close();
return recipes;
}
I have tried upgrading the database version and looking at other similar questions on StackOverflow, neither helped.
Thanks.
You forgot to put comma(,) in create table statement.
Instead of
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
It should be
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER, " + // Here you forgot to put comma(,) in this line
COLUMN_PARENT_BOOK + " TEXT" +
");";
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].