SQLite rawquery - android

I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor

Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'

To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

Related

Retrieving specific table items from sqlite database

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());
}
}

Android Sqlite no result

what do you think my problem is.
I am querying a sqlite database.
This code doesn't give any result.
String sql = " select _id from MYTABLE where _id = ? ";
Cursor cur = mDb.rawQuery(sql, new String[] {"5653"}) ;
but if I am executing the query without parameters like this:
String sql = " select _id from MYTABLE where _id = 5653 ";
Cursor cur = mDb.rawQuery(sql, null) ;
One row is returned as expected.
Many thanks.
That happens because the values are bound as strings, and that column is (i am guessing) an int. so the where clause will end up being
where _id = "5653"
From rawQuery javadoc for selectionArgs -
You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Try this:
String sql = " select _id from MYTABLE where _id = '5653' ";

executing rawquery with WHERE Clause from another Activity to recieve Table Values

I am having a problem in SQLiteDatabase. I want to access the database table created in one Activity from another Activity.However when I use WHERE clause the query is not executing.
I am referring sambleDB from CropInfoListclass.
These are some codes.
String[] item = {getIntent().getExtras().getString("item")};
Cursor c = CropInfoList.sampleDB.rawQuery("SELECT * FROM "+ TableName +" WHERE "+ name +"=?", item);
String Name = c.getString(c.getColumnIndex("name"));
String Type = c.getString(c.getColumnIndex("type"));

Why is my query crashing?

I've written the following DB query.
However, the app crashes when I access the list activity that displays the results.
I've traced the error to the method below (other simpler query methods work just fine):
public Cursor fetchInterface_HSE_Entries(String string) throws SQLException{
String[] columns = new String[] {KEY_ROW_ID_INTERFACE, KEY_TEXTVIEW_VALUE, KEY_CATEGORY_OPTIONS, KEY_WORKSCREEN};
String whereClause = KEY_WORKSCREEN+"=" + string;
Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
And this is part of my error log:
12-31 16:13:38.851: E/AndroidRuntime(480): Caused by: android.database.sqlite.SQLiteException: no such column: testInterface1: , while compiling: SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
Try with:
String whereClause = KEY_WORKSCREEN+"='" + string + "'";
You need to quote text values in your queries, otherwise they will be interpreted as column names (or functions, or whatever).
Note that this is not safe against SQL Injection attacks, you should be using bind variables.
String whereClause = KEY_WORKSCREEN+" = ?";
Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause,
new String[]{string}, null, null, null);
Because you do not put quotes around your whereClause.
Try:
String whereClause = KEY_WORKSCREEN+"='" + string + "'";
You can clearly see it in your error log:
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
should be:
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen='testInterface1'
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
As error says you don't have testInterface1 collumn in interfacetable table, i think you should have value instead of testInterface1 in your sql statement. Run your query in db, and you will see the same error.
You need to put your string value in the where clause into quotes.
Workscren is string edit your query and add single quotes. Key-workscreen+"="'+ string +'" like that

android: error on SQLiteDatabase rawQuery (fetching data)

So I have a SQliteDatabase mDb. It only has one column, and its data are Strings for previously saved inputs. I'm trying to populate all the data from mDb into a String[] for AutoCompleteTextView (so that the autocomplete is based on previous inputs), and here's my code to get all of the String.
public String[] fetchAllSearch() {
ArrayList<String> allSearch = new ArrayList<String>();
Cursor c = mDb.rawQuery("select * from " + DATABASE_TABLE, null);
c.moveToFirst();
if (c.getCount() > 0) {
do {
allSearch.add(c.getString(c.getColumnIndex("KEY")));
} while (c.moveToNext());
}
String[] foo = (String[]) allSearch.toArray();
if (foo == null) {
foo = new String[] {""};
}
return foo;
}
my CREATE_TABLE command is
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE;
..
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
But for some reason the line mDb.rawQuery(...) is giving me "no such table found" exception, and for the life of me I can't figure out why. Any pointers?
What is the value of DATABASE_TABLE?
If it is just a table name, then the create statement is incomplete because it doesn't specify the columns.
If it is a name plus column definitions, then the select will not work.
So, you need to use different text in the two places you used DATABASE_TABLE
Try using the SQLite3 command line program to try out your SQL. E.g.,
sqlite> create table foo;
Error: near ";": syntax error
sqlite> create table foo(col);
sqlite> select * from foo(col);
Error: near "(": syntax error
sqlite>
Use SELECT column_name FROM table_name.
Avoid using * in the query as it might cause the problem related to primary key.

Categories

Resources