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
Related
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.
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);
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
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
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