How to LIMIT the fetching of the rows in the database [duplicate] - java

This question already has answers here:
Using the LIMIT statement in a SQLite query
(3 answers)
Closed 10 years ago.
I have a query like this:
Cursor _cursor = mbd.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_SYLLABICATION, KEY_WORD, KEY_PARTOFSPEECH, KEY_MEANING, KEY_SPEAKWORD},
null, null, null, null, null, null);
I just simply want to limit the rows to fetch from the database.

According to the documentation, you pass the LIMIT clause as the eighth parameter to query:
Cursor _cursor = mdb.query(SQLITE_TABLE,
new String[] { KEY_ROWID, KEY_SYLLABICATION,
KEY_WORD, KEY_PARTOFSPEECH,
KEY_MEANING, KEY_SPEAKWORD },
null, null, null, null, null,
"10");

Try this
cursor = resolver.query(STORAGE_URI, projection,
Media.BUCKET_DISPLAY_NAME + "=?",
new String[] { folderName },
" _id asc limit " + num);
or try this
final String orderBy = Constants.TABLE_CONVERSATION_FIELD_DATE + " DESC";
final String limit= 10;
return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Related

Android SQLite get all rows where column contains string always returns -1

textAs the title describes I'm trying to get all rows from a table where strings of a column contains a string anywhere in it. But they way I'm doing it now always return -1 rows.
This is how i'm doing it now but I have no idea of what I might be doing wrong. Suggestions?
Cursor cursor = database.query(DBHelper.TABLE_RECENT, null, DBHelper.COLUMN_TEXT+ " LIKE '%"+club_id+"%'", null, null, null, null);
Just write cursor.moveToFirst(); before getting data from cursor or just under query line.
Hope it will help you.
I guess, you're mis interpreting the structure of query. the second parameter is what you want to select. such as "select column1, column2 etc. Here's a line from my code, and it works for me.
Cursor cursor = db.query(table_employees, new String[] {KEY_ID, KEY_NAME,KEY_DEPARTMENT, KEY_PHONE_NUMBER, KEY_SALARY}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
here "new string[] {key_id.....", the second parameter, is column names, that you wanted to select.
OR
alternately, you may simply do as:
String query = "Select * from "+DB_TABLE+ "Where" +column1 + "=" + t +"and"+ column2 + "=" +tt
db.rawQuery(query);
if you do something like,
String query = "Select * FROM Product where name LIKE '%" + Text + "%'"
Log.d("search query", query);
Cursor c = db.rawQuery(query, null);
c.moveToFirst();

WHERE clause in Android SQLite

String[] columns = new String[]{ KEY_NAME, KEY_NUM };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + name, null, null, null, null);
This is the code I am using for returning those columns which match a particular string I have passed in i.e. name. However, this does not work. Also, If I replace the 'where' clause by null, all the rows are returned correctly. Please Help. Thanks!
The source table rows are thus
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "surveyString";
public static final String KEY_NUM = "numOfQuestions";
You should pass the where values into the "selectionArgs" parameter in your query.
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=?", new String[]{name}, null, null, null);
Have you tried put ' between the variable?
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "='" + name + "'", null, null, null, null);
public void addUserNotes(String notes,int id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTES, notes);// Contact Phone Number
db.insert(TABLE_CONTACTS, null, values);
String s=Integer.toString(id);
final String[] whereArgs = {s};
db.update(TABLE_CONTACTS, values, "id = ?", whereArgs);
db.close(); // Closing database connection
}

Android sqlite helper error while getting data back

Hi all im using a sqlite helper class, but i have a little problem using a select statement.
I want to get the id of a datebase item by its name.
I use this select method:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
c.moveToFirst();
db.close();
return c;
}
And when i call this i use this:
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
id = c.getInt(c.getColumnIndex("_id"));
c.close();
}
And then is get this error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.
Can someone help me how to fix this?
1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
if (c.moveToFirst()){ //<--------------
do{ //<---------if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}while(cursor.moveToNext());
}
c.close();
}
2- not sure but looks in select query as '<variable>' are not there in where clause with variable
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
The issue appears to be here
"name=" <-It should be "name = "+name
Following should work
Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name}, null, null, null);
Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation. Maybe something like this
Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);
Thanks for your help, i found the problem. It was in the cursor method, the solution is:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
c.moveToFirst();
db.close();
return c;
}

need help with androids sql query

I have an error in that m
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Cursor myCursor=db.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE}
, KEY_ROWID , null, null, DATE+"="+currentDateTimeString, KEY_ROWID, null);
The query function by the androids api:
query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
What I am trying to do here is to say. give me all the data based on where the date equals
currentDateTimeString .
But I get an error on that statement..
dont ask me what the error is..when i remove the call to the method holding that query statement the error doesnt appear..so i guess it is an sqlexception
SOLVED MY ME:
Cursor myCursor=db.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE}
,DATE+"='"+currentDateTimeString+"'" , null, null, null , KEY_ROWID, null);
I am trying to do this
SELECT MONEY_FIGURE,SPENDING_DETAILS,DATE
FROM SpendingManagmentTable
WHERE Date=# currentDateTimeString
If the column type is not number then have to use with ''
date='1/1/2011' not date=1/1/2011
Cursor c = db.query(DATABASE_TABLE, new String[] {{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE},DATE+"='"+currentDateTimeString+"'", null, null, null, null);

Why is my getColumnIndex() returning -1?

Ok, so here is my database create statement:
create table entry (
_id integer primary key autoincrement,
date integer not null,
checknum integer,
payee text not null,
amount integer not null,
category text,
memo text,
tag text
);
After the datbase is created, and I make a call like:
mChecknum = cursor.getColumnIndex("checknum");
mChecknum is -1. I have pulled the database from the device and used SQLite Browser on it, and the checknum field is there.
Block around statement in question:
mDbHelper.open();
Cursor cursor = mDbHelper.fetchAll();
startManagingCursor(cursor);
COL_DATE = cursor.getColumnIndex("date");
Log.v("Main:123", "COL_DATE: " + String.valueOf(COL_DATE) );
COL_CHECKNUM = cursor.getColumnIndex("checknum");
Log.v("Main:125", "COL_CHECKNUM: " + String.valueOf(COL_CHECKNUM) );
COL_PAYEE = cursor.getColumnIndex("payee");
COL_DATE returns 1 and COL_PAYEE returns 2. Why is COL_CHECKNUM being ignored/passed over?
In my situation getColumnIndex was returning error on the column which had name which contained the "." symbol i.e.:
int colIndex = cursor.getColumnIndex("Item No.");
and despite the column "Item No." was inside the cursor (the debugger Watch showed it) trying to get the column index failed.
In my fetch/fetchAll database functions, I forgot to update the query with the new column.
For example, before i added the new column, my fetchAll code looked like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}
After adding the new column to the database, my fetchAll function looks like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_CHECKNUM, KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}

Categories