I want to return the rows in my database that have the attribute in one of the fields equal to the parameter to the method. My code is:
public Cursor fetchStatus(String status){
Cursor mCursor =
mDb.query(DATABASE_TABLE, new String[] {KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE, KEY_STATUS},
KEY_STATUS+ "= "+status, null, null, null, null)
;
if(mCursor!=null) mCursor.moveToFirst();
return mCursor;
}
I want to return the KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE and KEY_STATUS columns where the KEY_STATUS is equal to the parameter 'status'
Perhaps you may try something like this:
public object GetValues (string status)
{
string query = "SELECT KEY_COMPANY, KEY_POSITION, KEY_NOTES, KEY_WAGE,KEY_STATUS
FROM DATABASE_TABLE
WHERE KEY_STATUS = "'" +status+ "'" " ;
dbcomands part...
List<object> = execute db comand....
}
The error you specified in your comment might be caused by the lack of ' ' in you query. Just a thought.
Use PreparedStatement.
You can simply specify your query and set parameters in search query.
Related
so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
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
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM
Hello I am using a sqlite database in my android application, and I have question:
I am trying to get the last value text(thats the collumn) from the last row from the table TABLE_XYZ... but it does not work.. i am using the following code...what am I doing wrong?
another question is, how can I return two values instead of only one, when I want to get several values from the last row like column text and message?
private static final String KEY_MESSAGE = "message";
private static final String KEY_TEXT = "text";
...
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.close();
return cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
EDIT:
i hade some errors in my Query,, i fixed it, but still have errors:
String selectQuery= "SELECT * FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = cursor.getString( cursor.getColumnIndex(KEY_TEXT );
cursor.close();
return str;
while debugging I can see that cursor does have the right values inside... but when i try to get the column value with this command "cursor.getString( cursor.getColumnIndex(KEY_TEXT );"... it does not work...
you are closing cursor before getting it's value
try this :
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = "";
if(cursor.moveToFirst())
str = cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
cursor.close();
return str;
From the android documentation: http://developer.android.com/reference/android/database/Cursor.html
abstract void close()
Closes the Cursor, releasing all of its resources and making it completely invalid.
You are closing the cursor before returningthe string.
Like #whatever5599451 said you should not close the cursor before you get value. Also try a query like this:
String selectQuery = "SELECT column FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
You can specify the columns also specify to return only 1 row.
This will bring back only the column you are ordering by you can also specify more columns example:
String selectQuery = "SELECT column, column2, column3 FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
* means select all columns
to get the last column, use the name of the column instead of " * " (* means all, all the fields)
#Steve: do this:
String selectQuery= "SELECT " + KEY_TEXT + " FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
then you get just one String with the last record containing just the right column
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();
I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
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.
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;
}