Update Query not working in Android Sqlite - android

My Java code Update Data base Table
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+code;
Log.d("Qry", qq);
myDbHelper.updatequery(qq);
updatequery method
public void updatequery(String qry)
{
Cursor c = myDataBase.rawQuery(qry, null);
Log.d("Up", ""+c.getCount());
}
When i updated Data base the count return 0 and table not updated
I am using this Also but not work
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+"'"+code+"'";
Please Help Me how i can fix this problem
Thanks In Advance

Use execSQL() for such SQL and not rawQuery().
rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program.
execSQL() both compiles and runs the SQL program.
There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe.

To update sqlite query change
Cursor c = myDataBase.rawQuery(qry, null);
to this
myDataBase.execSQL(qry);

try to use this:
ContentValues values = new ContentValues();
values.put("Recieve", str);
db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });

Related

Update query not updating the column using SQLite on Android

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

Saving to sqlite using insert or update

i am using the below code to insert row to my db. every thing is fine but this method does not save row to the db. what is wrong with this code :
public void insert(Restaurant rest) {
String[] args = { String.valueOf(rest.getId()), rest.getName(),
rest.getDescription(), rest.getAddress(), rest.getTel1(),
rest.getTel2(), rest.getTel3(), rest.getEmail(),
String.valueOf(rest.getCategory()),
String.valueOf(rest.getRegion()) };
m_db.rawQuery(
"INSERT OR REPLACE INTO restaurant(id,name,description,address,tel1,tel2,tel3,email,category,region) VALUES(?,?,?,?,?,?,?,?,?,?)",
args);
}
Use execSQL() and not rawQuery() for raw SQL that modifies the database.
rawQuery() alone won't execute the SQL; you'd need to call one of the moveTo...() methods on the returned Cursor to execute it.

Quering SqlLite database where clause Android

Hi I am developing an android app.I am trying to query from the database. I need to fetch everything from the table TASK where dbDate = AlarmDate and dbdTime = AlarmTime.
c = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime= '"+Alarmtime+"'", null);
The problem is ,the cursor c is null.
I am not sure where I am going wrong in the query. Please Help.
Thanks!
Android has binding method to avoid sql inject. You can use the second parameter to provide the variables of SQL.
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = ? AND dbTime = ? ", new String[]{AlarmDate, AlarmDate});
Going by your comment 'I have used db = openOrCreateDatabase("Globus", 0, null); where Globus is the db name', you are not using SQLite properly with android.
What you should be doing is creating class which extends SQLiteOpenHelper, then make sure you override the onCreate and onUpgrade methods, these are the methods where you create tables and make changes, it has been said a hundred times on here so I will provide a link to a tutorial: http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android
When you do database operations, on the class call getWritableDatabase (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase())
I say call getWritableDatabase because that way you don't need to worry if you can write to it, a writable database is also readable. Just FYI. Ask away for more details.
This should be the process of reading (writing is the same, just use what method you want instead of query):
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//this should lock the tables you are reading
Cursor c = db.rawQuery("select 1 where 1=?", new String[]{"1"});
if(c.moveToFirst()){
do{
//Do what you want with the row
}while(c.moveToNext());
}
c.close();
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Here is the source code of a database helper I wrote, maybe it will help, read through it, understand how it works. https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/ApplicationDataDbHelper.java?at=master
And if you want to know the reason the open methods exist read through this code
(This class was made from the help of someone elses code)
https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/SDCardSQLiteOpenHelper.java?at=master
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime = '"+AlarmTime+"'",new String [] {});
Make sure you have gotten a readable database for 'db' or it will return null everytime.
Also change the end of your raw query to new String [] {}
Hope this helps, this is what I use in my applications.

Update table using rawQuery() method does not work

I tried the following SQLite query:
int idServizo = 150;
String whereClause = id_servizio+" = '"+idServizio+" ' ";
ContentValues cv = new ContentValues();
cv.put("sync", 1);
int r = dbManager.updateTable("myTable", cv, whereClause);
Where fields sync and id_servizio are both integer.
The method updateTable is:
public int updateTable(String table, ContentValues values, String whereClause){
int r = mDb.update(table, values, whereClause, null);
return r;
}
// mDb is SQLiteDatabase object
All this works good.
But if I try this with the rawQuery() method:
public Cursor RawQuery(String sqlQuery, String[] columns){
return mDb.rawQuery(sqlQuery, columns);
}
The table is not updated! even if no error occurs.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
dbManager.RawQuery(updateQuery, null);
Why does this not work?
This is because when a rawQuery is executed cursor is returned. Without the call to cursor.moveToFirst() and cursor.close() the database won't get updated.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
Cursor c= dbManager.rawQuery(updateQuery, null);
c.moveToFirst();
c.close();
I dont know the need to call moveToFirst() but this works fine and the database gets updated.
Problem solved.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Can't works because rawQuery runs the provided SQL and returns a Cursor over the result set.
If I want to return a table I have to use rawQuery, otherwise no!
Increase the value of a record in android/sqlite database
You should use db.execSQL() instead db.rawQuery().
Instead of doing this:
Cursor c= dbManager.RawQuery(updateQuery, null);
c.moveToFirst();
c.close();
You just need this:
dbManager.execSQL(updateQuery, null);
----------------------------------------------------------------------------
Posting answer because sometimes many people (like me) not reading comments.
Most popular answer is not correct but Yaqub Ahmad's comment is correct.
Answer from CommonsWare explained in this answer:
rawQuery() is for SQL statements that return a result set. Use
execSQL() for SQL statements, like INSERT, that do not return a result
set.
----------------------------------------------------------------------------
Documentation for execSQL:
public void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
Documentation for rawQuery:
public Cursor rawQuery (String sql,
String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Your update call formats the ID as string, while the rawQuery call formats is as number.
Assuming that the ID in the table indeed is a string, use:
String updateQuery = "UPDATE myTable SET sync = 1 WHERE id_servizio = '" + idServizio + "'";

fetching value from database and displaying it in a TextView in android

How can fetch values form database and display it in a textview in android?
Good to see you've given it some thought and tried on your own.
http://developer.android.com/guide/topics/data/data-storage.html#db has some good info on using SQLite on Android
It's also used in the Notepad tutorial: http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html
I personally learned by using part of the guide from the "Hello, Android" book. The source code is available at: http://www.pragprog.com/titles/eband3/source_code - the SQL example is the one called 'Eventsv1'
You need SQLiteOpenHelper class to fetch readable instance of SQLiteDatabase in android. Then using query method you can get Cursor object of you query.
Can you explain more about what you want to do?
Try this,
Cursor c = db.query(TABLE_NAME, columns, null, null, null, null, null);
Then write
if(c!=null) {
c.moveToFirst();
while(!c.isAfterLast()) {
String col1Value = c.getString(1);//here you get col1 value
String col2Value = c.getString(2);//here you get col2 value
c.moveToNext();
}
c.deactivate();
c.close();
}

Categories

Resources