Retrieving specific table items from sqlite database - android

I have a SQLite database that I am trying to query in order to find all the items of a specific type. Here is the function that I am calling in order to query my database:
Cursor c = dbi.DBGrabTable("LEGS",ExerciseListActivity.this);
Here is the function definition:
public Cursor DBGrabTable(String type, Context ctx){
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + type;
DBContract.DBHelper mDBHelper = new DBContract.DBHelper(ctx);
SQLiteDatabase rdb = mDBHelper.getReadableDatabase();
Cursor c = rdb.rawQuery(query,null);
if (c != null)
return c;
else
return null;
}
The error that I am getting is as follows:
android.database.sqlite.SQLiteException: no such column: LEGS (code 1): , while compiling: SELECT * FROM Exercises WHERE Type=LEGS
Therefore I am thinking it has something to do with the SQL query. I am unsure why it is saying "no such column: LEGS" I am trying to query my database to look in my Table named "Exercises" under the column header "Type" and select all the items that have the word LEGS in that column.
Can anyone see what I am doing wrong? A huge thanks in advance!

1 - Check the table definition whether the column and table name available.
2 - If table and column is available and type is text please change your sql query and try it.
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + "'" + type + "'";

Use this query and make sure in maintenace of space and inverted comma. Check your Column name(Type) in TABLE_EXERCISES.
"SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type = '" + columnValue + "'";
move the cursor till last row of table.
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
} while (cursor.moveToNext());
}
}

Related

Insert if not exists: SQLite

I want to insert data if that headline doesn't exist yet in the database.
This is the error I'm getting for the written query:
near "with": syntax error (code 1): , while compiling: SELECT * FROM movie WHERE headline=Albert Collen
Code:
public boolean Insert(Item item) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline=" + item.getName() , null);
if (cursor.moveToFirst()) {
} else {
contentValues.put("name", item.getName());
long result = sqLiteDatabase.insert(TABLE, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
cursor.close();
sqLiteDatabase.close();
return true;
}
You should use query parameters
rawQuery("SELECT * FROM movie WHERE headline = ?", new String[] {"Albert Collen"});
to avoid having to escape quotes and other chars.
First of all, result query is wrong. All the string constants are to be quoted, like this
SELECT * FROM movie WHERE headline='Albert Collen';
So, try to compose query like this, perhaps it will help
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline='" + item.getName() + "'" , null);
But concatenating a query is not a good idea because it makes at least SQL-injections possible.
For example, it can cause problems when item.getName() contains following line "'; drop table movies;"
Better option would be using bind query variables. Unfortunately, I'm not familiar with how to use java-android with sqlite, so it is better for you to check how to use such a queries in android

Update the table when the count of particular value is more than one in SqLite

I have a table and I want to update the existing values when the count is greater is 1.
Here is my code :
public int getCount(String clues) {
Cursor c = null;
try {
db = this.getReadableDatabase();
String query = "select count(*) from " + TABLE_NAME + "where CLUES_VALUES = ?";
c = db.rawQuery(query, new String[] {clues});
if (c.moveToFirst()) {
return c.getInt(0);
}
return 0;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
I am checking based on the column "CLUES_VALUES" . I am getting the values from database and checking if it contains more than one similar value in the column of "CLUES_VALUES" . If it contains then it will update the entire row else it won't.
when I am executing the code, I am getting below error
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: select count(*) from puzzl_tablewhere CLUES_VALUES = ?
Clues_values column contains "String values"
I don't know where I am missing. Please help .
You're missing a space in front of "where".
String query = "select count(*) from " + TABLE_NAME + " where CLUES_VALUES = ?";
I think what you are missing is simply a space after table name and before where.
String query = "select count(*) from " + TABLE_NAME + " where CLUES_VALUES = ?";

Querying a SQLite table to return rows with a specific ID

This is the method that is suppose to take a long ID and return the row that matches the given id but something is wrong with my query and I cannot figure it out. Any ideas? (the column containing the id values is called "ID")
public Cursor getAllData (long ID) {
SQLiteDatabase db = this.getWritableDatabase();
long thisID = ID ;
Cursor result = db.rawQuery("select * from WHERE ID = " + thisID + DataTableName,null);
return result;
}
Your SQL is malformed. The right format is select <columns> from <table> where <condition>. You will get something like select * from where <condition><table>.
Another piece of advice - don't use string concatenation to build SQL queries. It's a very bad practice and opens up your app to SQL Injection attacks. Use the parameterised version of the query methods to prevent this.
You should do it as follows :
Cursor result = db.rawQuery("select * from " + DataTableName + " WHERE ID = "+thisID,null);
And what #Danail Alexiev wanted to say to you I guess is this :
Cursor result = db.rawQuery("select * from " + DataTableName + " WHERE ID = ?",new long[]{thisID});

android sql cursor error

Im playing with sql in android and found this issue:
Im reading data from my database:
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
SingleAppModel singleAppModel = new SingleAppModel();
and when I try to get cursor.getInt(3) over here:
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
singleAppModel.setId(cursor.getInt(0));
singleAppModel.setAppName(cursor.getString(1));
singleAppModel.setPackageName(cursor.getString(2));
singleAppModel.setState(cursor.getInt(3) == 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
db.close();
It returns error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
Weird is that if I delete line where Im calling cursor.getInt(3), it works.
Colum with that value exists and Im sure its of type INTEGER.
Also the value of cursor.getColumnCount() is 4 and value of cursor.getCount() is 1 ... so there are definetly some data...
Any advice?
Thankyou.
Rather than using * I suggest you to use,
cursor = db.rawQuery("SELECT COL0, COL1, COL2, COL3 FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
Use the appropriate values for COL0, COL1, COL2, COL3 according to your table.
That way you make sure that the order of the columns fetched in the query.
But according to this,
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
I need more information to confirm, can you add your table schema, according to the issue there is no 3rd column in the database raw.
Edit:
This can be a small programmer mistake,
Look out for the onCreate and onUpgrade methods in SQLiteOpenHelper implementation

SQLite query compare content Values

How can I compare column content values? So if content values contain "ted" return all data in cursor.
public Cursor listNotes() {
String username = session.getUser();
String query = "SELECT * FROM Task WHERE " +help.Column_owner+ " = " +username ;
Cursor c = db.rawQuery(query, null);
return c;
}
Here is the error, I am trying to compare username to the content values in the column_create but its not working
no such column: ted (code 1): , while compiling: SELECT * FROM Notes WHERE column_owner = ted
username must be enclosed in apostrophes ('), because it is a string!
Correct your code like this:
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = '" +username + "'";
Or, better, use a bound parameter (in this case, Android takes care of the apostrophes for you and you're less prone to SQL injection - and, last but not least, you use less string concatenations):
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = ?";
Cursor c = db.rawQuery(query, new String[]{username});

Categories

Resources