I am working in an android application and I am using sqllite in my application. I want to update my sql with a query that contains case statement. Please suggest me a correct solution to execute this query and return me an int value to confirm if the table is updated successfully.
My query ::
UPDATE TblAgencies SET Selected= CASE WHEN ID=6 THEN 1 ELSE 0 END
update TblAgencies set Selected = (ID == 6); will do this.
As to "did the update work correctly" -- that's standard API work, nothing to do with the query itself.
I wont do the programming for you but here how you do it.
int res = db.update(table, values, whereClause, whereArgs);
if(res>0) etc...
try
{
database=openOrCreateDatabase("solutiondb", MODE_PRIVATE, null);
database.execSQL("update patientdetails set name='"+naMe+"',dob='"+DOB+"',gender='"+genDer+"',height="+heiGht+",weight="+weiGht+",bmi="+BMI+",bloodgroup='"+bloodGroup+"',profession='"+proFession+"',address='"+addRess+"',contact="+contactNumber+",smoking='"+smoKing+"',drinking='"+drinKing+"',maritalstatus='"+maritalStatus+"',physician='"+phySican+"' where id="+patientId+"");
Toast.makeText(PersonalInformationActivity.this, "Your Personal Details Are Saved Successfully", Toast.LENGTH_LONG).show();
dialog.dismiss();
intent=new Intent(PersonalInformationActivity.this, PersoxcsdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
database.close();
}
catch(SQLException exception)
{
}
Related
I have written the following code to update some information in a database using SQLite. The idea is to update a value (userAverageTime) in case the entry already exist, or make a new record if the entry does not yet exist.
Here is the code:
public void updateTableLevelsAverageTime(DatabaseOperations dop, LinkedList<Level> levels) {
SQLiteDatabase SQ = dop.getWritableDatabase();
String selection = KEY_NUMBERS + " = ?";
for (Level level: levels) {
String[] args = {level.toString()};
ContentValues cv = new ContentValues();
cv.put(KEY_AVERAGE_TIME, level.getAverageTime());
int result = SQ.update(TABLE_LEVELS, cv, selection, args);
if (result == 0) {
//If the entry doesn't exist, it must be a new level... thus add it with 0 as userseconds
ContentValues cv2 = new ContentValues();
cv2.put(KEY_NUMBERS, level.toString());
cv2.put(KEY_AVERAGE_TIME, level.getAverageTime());
cv2.put(KEY_USER_TIME, 0);
SQ.insert(TABLE_LEVELS, null, cv2);
Log.d("Database operations", "Row added");
}
else {
Log.d("Database operations", "Row updated");
}
}
SQ.close();
}
(KEY_*** are column names that are defined elsewhere in the code)
I was wondering if this was the best approach, though. The code takes quite some time to run.
I have read somewhere that if you want to update data you can do this batch-wise. But can you do this as well when you want to update only if a record exists and when you want to add the record if it doesn't exits?
You can use a REPLACE INTO command as you would use an INSERT INTO one, in order not to have to check if the record exists and execute the corresponding UPDATE or INSERT INTO command.
SQLite will first delete the row (if existing) and then insert it newly.
Therefore you can write an execSQL() instruction which uses the REPLACE INTO command where you are currently executing a query and then deciding which command to execute next.
The REPLACE INTO will help you skipping all that logic.
I find it really useful.
I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.
In my app, when the activity is destroyed, I want to update a column value to 0. For that I have written the query, but it seems not to be working for me, because when ever I start the app I get the same old values.
Code
public void resetSelectOptions() {
database = DatabaseManager.getInstance().openDatabase();
String query = "Update " + TableName + " SET " + Selected_Option + "=0";
try {
database.rawQuery(query, null);
}
catch (SQLiteException e) {
}
DatabaseManager.getInstance().closeDatabase();
}
How can I fix this problem?
Use this method to updating the rows,database.update() and
rawQuery is used to select query.
rawQuery() only executes queries (SELECT).
For any other SQL command, use execSQL().
So, simply convert this
database.rawQuery(query, null);
to this
database.execSQL(query, null);
It is not correct that the rawQuery() method executes only SELECT queries, it doesn't, but it is unnecessary to use it for an update, because you don't have any result - what to be iterated with the result Cursor at the ends, so try to use the execSQL() method. For more information take a look at this SO question android.database.sqlite.SQLiteDatabase.rawQuery() is not updating a DATETIME column with a SQLite datetime() function
I am having trouble getting a null value from SQLite database using Android.
My database has 10 columns. From column 1 to 8 all are filled with values. But there are several rows where the values in column 9 and column 10 are either null or some number.
I want to check:
String selectQuery = "SELECT * FROM products WHERE barcodeId='" + id + "'";
Cursor myCursor = db.rawQuery(selectQuery, null);
if (myCursor.moveToFirst()) {
//checking to see if there is something in column 9
if(myCursor.getString(8) != null){
// do soemthing
}else {
// if there is nothing do something
}
//checking to see if there is something in column 10
if(myCursor.getString(9) != null){
// do soemthing
}else {
// if there is nothing do something
}
}
Can some one provide a working code according to my example with column 9 and 10 in my table.
A brief explanation will also be welcomed.
Thanks
I don't know if Cursor.getString() will return a null or not. The docs don't say, it may just return an empty string. You should use Cursor.isNull() instead to check for a null value in your column.
Thanks DavidCAdams that fixed my problem.
Here is my code if someone is interested in it.
if(myCursor.isNull(8)){
Log.w("No value", "Cell is empty");
}else{
Log.w("Value is present", "There is a value");
}
if(myCursor.isNull(9)){
Log.w("No value", "Cell is empty");
}else{
Log.w("Value is present", "There is a value");
}
I wrote the below code for compare the record with the database record.its comparing but inserting all the records
public void onClick(View v) {
if(v.equals(add))
{
if(ifExisting())
{
insert();
Log.e("Data Inserting","true");
Intent i=new Intent(AddCategory.this,ShareFolioActivity.class);
startActivity(i);
//Toast.makeText(AddCategory.this, "Already exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(AddCategory.this, "Already exists",Toast.LENGTH_LONG).show();
Log.e("Data Inserting","false");
}
}
}
boolean ifExisting() {
Log.e("wquery","SELECT * FROM sharelist WHERE category='"+category.getText().toString()+"'");
Cursor c = db.rawQuery( "SELECT category FROM sharelist WHERE category='"+category.getText().toString()+";'",null);
if(c.getCount()==-1)
{
Log.e("Condition true","true");
return false;
}
else
{
Log.e("Condition true","false");
return true;
}
}
You have if(ifExisting())
{
insert();
shouldn't it instead be if(!ifExisting())
{
insert();
Otherwise you are inserting if it exists.
You seem to be expecting that c.getCount() will be -1 if the query returns 0 rows. Why wouldn't it return 0? (I don't remember seeing a case where it returns -1, but perhaps my memory is faulty.)
In any case, checking for c.getCount() <= 0 would seem to be safer.
Also, this query
Cursor c = db.rawQuery( "SELECT category FROM sharelist WHERE category='"+category.getText().toString()+";'",null);
is malformed -- look at the end where you have ";'". You want to have "'" there. (Query strings that are passed to rawQuery must not end in a semicolon; otherwise, "';" would be the correct choice.)
As others have said to you on other threads, you really don't want to be making queries by concatenation; using the selectionArgs argument is a much safer way to pass query values.