Passing parameters into SQLite querys [duplicate] - android

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.

Related

how to fetch data from sqlite by name

I just started learning of android and come to section of Database and I inserted same record in it but now I want to fetch data from database only by name and display it in textview.
Help me
Thank You in advance
Please follow developer document.
https://developer.android.com/training/basics/data-storage/databases.html
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_SUBTITLE
};
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
You access data by using a query which returns a Cursor.
A Cursor is like a spreadsheet table that contains columns and rows.
You tell the query what columns you want and imply the rows that will be returned via an optional WHERE statement.
The simplest of queries is base upon the SQL SELECT * FROM <table>;. This will select all columns (i.e. * means all columns) from the table as specified by <table> ( where would be replaced by a valid table name).
If you want specific columns then ***`` should be replaced with a comma delimited list e.g.SELECT name, address FROM would return a **Cursor** containing all the rows from the table with only the **name** and **address** columns from the table specified by`.
If you want to filter the rows returned then you can add a WHERE clause. e.g. SELECT name,address FROM <table> WHERE name = 'Fred', would return a Cursor containing only the rows that have Fred as the name column with only the name and address columns.
You cannot just type the SQL statments you need to either use the SQLiteDatabase rawQuery or query methods if you need to return a cursor.
Using rawQuery
rawQuery takes two parameters, the first being the SQL as a string, the second optional arguments (not covered here, so null will be used).
To obtain a Cursor with columns name and address and with only rows that have Fred you could use, assuming the table is called mytable :-
`Cursor mycursor = db.rawQuery("SELECT name,address FROM mytable WHERE name = 'Fred'";);`
where db is an instance of an SQLiteDatabase object.
However, rawQuery is not recommended as it is open SQL injection. rather it is recommended only for situations where it has to be used.
Using query
query has a number of overload variations as can be found here SQLiteDatabase.
For this example query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) will be used.
String table, is the name of the table to be queried.
String[] columns, is an array of column names.
String selection is the where clause (null for no where clause).
String[] selectionArgs is an array of arguments that replace the ? placeholder.
The rest of the parameters will be null as these are features that are not being utilised.
As such the code could be :-
String tablename = "mytable";
String[] columns = {"name", "address"};
String whereclause = "name=?"; //note use of placeholder ?
String[] whereargs = {"Fred"};
Cursor mycursor = db.query(tablename,
columns,
whereclause,
whereargs,
null,null,null
);
where db is an instance of an SQLiteDatabase object.
Accessing the Cursor
mycursor contains the data or perhaps not if there isn't a column with the name Fred.
The number of rows in the cursor can be obtained by using:-
int rowsincursor = mycursor.getCount();
Note! A returned Cursor will not be null. (a very common mistake)
To access the data you have to move through the Cursor. Initially the Cursor is before the first row. If you only expect or want the only/first row then you can use the Cursor moveToFirst method.
See Cursor for more move... methods etc
Once the Cursor is appropriately positioned you can use Cursor get methods to get the data. e.g. getString(int columnindex) will return the data as a String. columnindex is a 0 based offset of the column to be accessed. Using the Cursor's getColumnIndex(String columnname) can be used to eliminate errors made by miscalculating offsets.
As such the following could be used to set a TextView (note intentionally over cautious)
if (mycursor.getCCount() > 0) {
if (mycursor.moveToFirst()) {
mytextview.setText(mycursor.getString(mycursor.getColumnIndex("name")));
}
}
mycursor.close() // You should always close a cursor when done with it.

Can't extract integer from cursor after preforming sqlite query in Android

I'm working on an small android app that maintains a small database of tools which I lend out to other people.
As part of the app, I am incorporating an sqllite database, where I am having a bit of trouble performing queries and working with cursors once the queries have been executed.
The code in question is as follows:
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
return Integer.parseInt(cursor.getString(3));
The contract for the database is as follows:
public class ToolStatisticContract {
public static final class ToolStatisticEntry implements BaseColumns {
public static final String TABLE_NAME = "tooltable";
public static final String COLUMN_TOOL_NAME = "toolName";
public static final String COLUMN_LIFESPAN = "lifespan";
public static final String COLUMN_USAGE = "usageTime";
}
}
I am essentially trying to extract out the value from COLUMN_USAGE, which seems to be producing errors with regards to parsing the value to an integer. The value in the COLUMN is actually an integer typecasted as a String from a previous segment of code, so I'm fairly certain the error is encompasssed with the code snippets above.
Thanks again in advance for all your help!
The code in question is as follows
The net SQL statement is something like:
SELECT toolName FROM tooltable WHERE toolName = ?
And there is no column with index 3, since you are only returning 1 column.
You need to:
Have usageTime in your column list (COLUMNS)
Move the Cursor to a valid row (as it initially is positioned before the first row)
Pass getInteger() the value that lines up with COLUMNS to retrieve usageTime
You could use the following. This uses null instead of columns, which will get all columns (i.e. resolves to SELECT * FROM table). It checks that a row has been returned and only then does it try to get the data. It also closes the cursor (you should close a cursor when done with it). It uses cursor.getInt() to get the integer value rather than convert it from a string to int. It assumes that you'll only get 1 row (if no rows then 0 will be returned).
int returnvalue = 0;
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, null,
selection, selectionArgs, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
returnvalue = cursor.getInt(2);
//or returnvalue = Integer.parseInt(cursor.getString(2));
}
cursor.close();
return returnvalue;
Note! I haven't checked this just coded it from memory, so apologies for the odd mistake.
To do the above using specific columns then you could use:-
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_USAGE };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
In which case the column index would be 0 (that is the index is according to the column's in the cursor). However it might be better to use, the following which gets the column index according to the column's name:-
cursor.getInt(cursor.getColumnIndex(COLUMN_USAGE);
The easiest way to read a single value from the database is to use a helper function that allows you to avoid having to handle cursor objects:
String query = "SELECT usageTime FROM tooltable WHERE toolName = ?";
String[] selectionArgs = { tool };
long returnvalue = DatabaseUtils.longForQuery(mToolDb, query, selectionArgs);

How to query using SQLiteDatabase.query

How can I make query using SQLiteDatabase.query ?
"Select * from table where col1 = something AND col2 IS NOT NULL"
I tried it by putting the col2 with a =? in selection String and NOT NULL in selection argument but it doesn't work.
Please tell me where m going wrong.
selectionArgs is an array of strings, and can be used only for string values.
When you use col2 = ? with the string NOT NULL, you are telling the database to check if the column's value is the eight-character string "NOT NULL".
You must write col2 IS NOT NULL directly into the selection string:
db.query("MyTable", null,
"col1 = ? AND col2 IS NOT NULL",
new String[] { "something" },
null, null, null);
You can use Cursor and rawQuery
Cursor c=db.rawQuery(your_query,null)
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns
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
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
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
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
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
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.
So you can try like this
String[] args = { "first string", "second#string.com" };
Cursor cursor = db.query("TABLE_NAME", null, "name=? AND email=?", args, null,null,null);

SQL Sorting number - ANDROID

public static final String KEY_HIGH
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_HIGH + " INTERGE);"
);
}
public long createEntry(String high) {
ContentValues cv = new ContentValues();
cv.put(KEY_HIGH, high);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
String[] columns = new String[]{KEY_HIGH,KEY_NAME};
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null, KEY_HIGH + " DESC");
I am trying to sort by the column KEY_HIGH, however, the result came out like this:
4
3
2
10
11
1
How do I sort them as numbers from highest to lowest?
thanks.
From the Android docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Added in API level 1
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns 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 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 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 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 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 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.
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
See Also
Cursor
Note that the final is named orderBy. This is where you can specify which column (or columns) to sort on. Also note that you do not need to include the "ORDER BY" keywords that you would use in a SQL statement.
I was having the same problem.It has a very simple solution:
In your CREATE_TABLE statement do this: " INTEGER, "+KEY_HIGH+ //your remaining things.
no need for the comma after the last null
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null + " ORDER BY " + KEY_HIGH + " DESC");

Android sql query using WHERE clause

Dear Stack Overflow Community,
I have a question regarding how to incorporate a WHERE clause when querying a sql database in Android. My goal is to return specific records from my database where the date picked by a datepicker matches the date stored.
Here is my code:
private static String datePickerDate = "3/29/2011";
private static String[] FROM = { _ID, NAME, PRICE, DATE, TIME };
private static String ORDER_BY = TIME + " DESC ";
private static String WHERE = DATE + "is like " + datePickerDate;
private Cursor getEvents(){
// Perform a managed Query. The Activity will handle closing
// and re-querying the cursor when needed
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
My questions are thus:
Where does my "WHERE" statement go?
And is my "WHERE" statement correct?
The documentation I found for db.query doesn't specify if a "WHERE" clause can be used, it just specifies that a "HAVING" clause is possible, but I don't quite think that's what I'm wanting.
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
The selection represents your WHERE clause.
From the doc
selection 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.
So you can try this (untested):
private static String WHERE = "DATE like ?";
db.query(table, columns, WHERE , new String[] { datePickerDate }, groupBy, having, orderBy)
If you want to use the WHERE clause, I would suggest using the raw query function in the SQLiteDatabase class, shown here.
This way, you can have the raw query typed out (or in segments) as if you were doing it naturally with SQL.
EDIT: On a side note, the "selection" parameter of the query() function corresponds to the WHERE clause, as noted here
About where you're "WHERE" goes - look here
And regarding the second part, I think you miss the qouts before and after the value, it should be .. like '3/29/2011' and not .. is like 3/29/2011

Categories

Resources