Why is my query crashing? - android

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

Related

syntax error in "SELECT DISTINCT _id near "SELECT"

If someone knows a better way to get a rowId from text in the row, please let me know.
I've been running around in circles with this and I know it's probably something simple, but I can't figure it out. Hoping someone can tell me what I'm doing wrong. I'm getting an error running this SQLite code:
String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol=" + name;
Cursor c = db.query(true, masterName, ALL_KEYS_MASTER, where, null, null, null, null, null);
The error points to the second line.
"name" is a string variable (in this case it's "Mary"). The exact error I'm getting is:
SQLiteLog: (1) near "SELECT": syntax error in "SELECT DISTINCT _id, masNameCol, masTotalTimeCol FROM masterRecord WHERE SELECT rowid, * FROM masterRecord WHERE masNameCol=Mary"
I've tried every syntax change I could find and think of, and it never changes the error. I'm just trying to get the rowId of the row so I can change a value in another column.
Use rawQuery(), not query().
You are trying to specify the entire SQL statement, which is what rawQuery() is for. query() assembles the SQL statement from pieces, and your one piece (where) is not just the WHERE clause.
Use placeholders for queries:
where = "masNameCol = ?";
whereArgs = new String[] { name };
columns = new String[] { "rowId" , /* all other column names you are interested in */ };
Cursor c = db.query("mytable", columns, where, whereArgs, null, null, null);

Passing parameters into SQLite querys [duplicate]

I am using the query method of SQLiteDatabase. How do I use the query method?
I tried this:
Cursor cursor = sqLiteDatabase.query(
tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);
tableColumns - columns parameter is constructed as follows.
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
If we need to get all the fields, how should the column parameter to be constructed. Do we need to include all the Field Names in String array?
How do I properly use the query method?
tableColumns
null for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1
whereClause
the part you put after WHERE without that keyword, e.g. "column1 > 5"
should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs
whereArgs
specify the content that fills each ? in whereClause in the order they appear
the others
just like whereClause the statement after the keyword or null if you don't use it.
Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClause though)
This is a more general answer meant to be a quick reference for future viewers.
Example
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Explanation from the documentation
table String: The table name to compile the query against.
columns String: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data
from storage that isn't going to be used.
selection String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing
null will return all rows for the given table.
selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.
groupBy String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.
having String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause all row
groups to be included, and is required when row grouping is not being
used.
orderBy String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.
limit String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Where clause and args work together to form the WHERE statement of the SQL query. So say you looking to express
WHERE Column1 = 'value1' AND Column2 = 'value2'
Then your whereClause and whereArgs will be as follows
String whereClause = "Column1 =? AND Column2 =?";
String[] whereArgs = new String[]{"value1", "value2"};
If you want to select all table columns, i believe a null string passed to tableColumns will suffice.
if your SQL query is like this
SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5 ORDERBY col-2 DESC LIMIT 15;
Then for query() method, we can do as:-
String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";
query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
db.query(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID, here = is the where clause. To select all values you will have to give all column names:
or you can use a raw query like this
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);
and here is a good tutorial for database.

Performance difference between a query() and rawQuery() method in Android

What is the difference between using a
rawQuery(String sql, String[] selectionArgs)
and
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
in android?
From my understanding query() method should in turn convert its parameters to form a sql query. So, would rawQuery() method give us better performance over query()?
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 .
Another way to perform a query is to use a db.query method. A query to select all employees in a certain department from a view would be like this:
public Cursor getEmpByDept(String Dept) {
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colAge,colDeptName};
Cursor c=db.query(viewEmps, columns, colDeptName+"=?",
new String[]{Dept}, null, null, null);
return c;
}
The db.query has the following parameters:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause

SQLite rawquery

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 .

how to use rawQuery in android

I have a database table with 3 columns: id, name, permission.
It looks like this:
1 Comics fun
2 Communication talk
3 Comics watch
I am trying to get the permission where the name is comics. I am using the following code in my database class(AppData.java):
private final static String DB_NAME = "safety_app_database"; // the name of our database
private final static int DB_VERSION = 1; // the version of the database
// the names for our database columns
private final String TABLE_NAME = "permissions_table";
private final String ID = "id";
private final String NAME = "name";
private final String PERMISSION = "permission";
and the method
public Cursor getData(){
return db.rawQuery("SELECT permission FROM permissions_table WHERE name = 'Comics', null);
}
and I'm calling this in my main class (safety.java). AppData is referencing AppData.java
appData.getData();
Is this the correct way to do it? I am unsure, and it is giving me an error whenever I try to call the sql query.
One typo mistake, you are not closing sql string with ". try this.
return db.rawQuery("SELECT permission FROM permissions_table WHERE name = 'Comics' ", null);
[EDIT: JAR belongs to 'Android 2.2' which does not allow modifications to source attachments on its entries]
The Jar of this class file blongs to container Android 2.0.1 which does not allow modifications
There is no need for a raw query. You can use one of the recommended SQLiteDatabase query methods and it would look like this:
db.query("permissions_table", new String [] {permission}, "name = \'Comics\'", null, null, null, null);
Try the following approach:
public Cursor getData(String arg) {
return db.rawQuery("SELECT permission FROM `permissions_table` WHERE name ="+arg, null);
}
Then just call the above method with the right parameter like this:
Cursor cursor;
cursor = getData ( "Comic" );
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 . Another way to perform a query is to use a db.query method. A query to select all employees in a certain department from a view would be like this:
public Cursor getEmpByDept(String Dept) {
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colAge,colDeptName};
Cursor c=db.query(viewEmps, columns, colDeptName+"=?",
new String[]{Dept}, null, null, null);
return c;
}
The db.query has the following parameters: String Table Name: The name of the table to run the query against String [ ] columns: The projection of the query, i.e., the columns to retrieve String WHERE clause: where clause, if none pass null String [ ] selection args: The parameters of the WHERE clause String Group by: A string specifying group by clause String Having: A string specifying HAVING clause String Order By by: A string Order By by clause

Categories

Resources