I'm trying to call user_id from sqlite database but I get this error
android.database.sqlite.SQLiteException: unknown error (code 0 SQLITE_OK): Queries can be performed using SQLiteDatabase query or rawQuery methods only.
at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
public Database user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT user_id FROM OrderDetails ;");
db.execSQL(query);
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
c.moveToFirst();
}
return user_id();
}
Please don't recommend another solution because I'm stuck with this for more than a day and I tried almost all solutions represented in stackoverflow and online
From: https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#execSQL(java.lang.String)
public void execSQL (String sql) Execute a single SQL statement
that is NOT a SELECT or any other SQL statement that returns
data.
So remove this line:
db.execSQL(query);
The method execSQL() is not used to execute queries that fetch rows, like SELECT statements. You can use it with INSERT, UPDATE, CREATE, etc.
Also, I think that you want to return the user's ids as a Cursor, right?
So why:
public Database user_id()
this returns a Database object (whatever this is).
Change the method to this:
public Cursor user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT user_id FROM OrderDetails";
Cursor c = db.rawQuery(query, null);
return c;
}
Related
I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0
This sourch code for my app:
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
//Cursor cursor = db.rawQuery("SELECT * FROM Note ", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
This function return nothing , but in debug mode , every single item was set .
Should it return a list of what i selected , i don't understand why and how it's not . Thanks for your help .
Use getReadableDatabase() for query purposes as follows.
SQLiteDatabase db = this.getReadableDatabase();
Please Read SQLiteOpenHelper documentation here for getReadableDatabase()
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk,
requires the database to be opened read-only. In that case, a
read-only database object will be returned. If the problem is fixed, a
future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object
will be returned in the future.
Read SQLiteOpenHelper documentation here for getWritableDatabase()
Create and/or open a database that will be used for reading and
writing. The first time this is called, the database will be opened
and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int)
and/or onOpen(SQLiteDatabase) will be called.
Once opened successfully, the database is cached, so you can call this
method every time you need to write to the database. (Make sure to
call close() when you no longer need the database.) Errors such as bad
permissions or a full disk may cause this method to fail, but future
attempts may succeed if the problem is fixed.
According to the getWritableDatabase() documentation, it clearly mentions that it will cache the database. So it's possible to retrieve data from a cached copy of your database. As same as make sure you've closed the database connection after your transaction.
Finally your code would be like this
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Note where Username = '"+acc+"'", null);
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
Try this
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM Note where Username " + " LIKE '%" + acc + "%'";
Cursor cursor = database.rawQuery(selectQuery, null);
int count = cursor.getCount();
database.close();
if(count==0)
{
return result;
}
else
{
if (cursor.moveToFirst()) {
do {
Note_DTO note = new Note_DTO();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setDate(cursor.getString(1));
note.setUser(cursor.getString(2));
note.setContent(cursor.getString(3));
NoteList.add(note);
} while (cursor.moveToNext());
}
I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question
Am just curious, is date a reserved word i SQLite? I have a column which is named date, and trying to run this query:
DELETE FROM cases WHERE date <= date('now','-1 day')
By doing this:
String query = "DELETE FROM cases WHERE date <= date('now','-1 day')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
But the cursor just gives me a false back, when calling moveToFirst. But in my database there are actually rows that are older than one day. Can anybody explain whats wrong here?
Thanks!
Yes it seems to be a reserved word.
look at: http://www.sqlite.org/lang_datefunc.html
date(timestring, modifier, modifier, ...)
It's strange to have a cursors form DELETE statement. Try to split the operation in
SELECT * FROM cases WHERE date <= date('now','-1 day')
then execute your checks
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
and then execute the DELETE part
DELETE FROM cases WHERE date <= date('now','-1 day')
This question is quite old but it deserves a proper answer.
No, date is not a reserved word.
The problem with your code is that you are using the method rawQuery() to delete from the table, which is not the way to do it.
rawQuery() should be used to return rows from the table in the form of a Cursor object.
Since your sql statement does not return any rows the method moveToFirst() returns false.
What you should use is the method delete() which returns the number of deleted rows:
int result = db.delete("cases", "date <= date('now', '-1 day')", null);
I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.