rawQuery selectionArgs not working - java

I'm trying to query a database with code:
Cursor cursor = db.rawQuery("select * from "+MoneyDBOpenHelper.TABLE_RECORD+" where "+ MoneyDBOpenHelper.ACCOUNT_ID+" = ?",new String []{"1"});
But it's not working at all,I didn't query any data.
While I abandon the usage of selectionArgs with code:
Cursor cursor = db.rawQuery("select * from "+MoneyDBOpenHelper.TABLE_RECORD+" where "+ MoneyDBOpenHelper.ACCOUNT_ID+" = 1",null});
It's working,and I got the data I want.I think those 2 lines of code should compose the same function but they didn't,am I doing something wrong?

1 is a number. "1" is a string.
This is a limitation of the Android dabase API; you should use parameters only for strings.

Related

error occur when try to SELECT in sqlite android

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

Android Sqlite select Query if value is zero or 0

I am trying to program a get a query that will show data from COURSE table if the values are :
course_id=0
or
semester_id=0
or
level_id=0
or
level_code=Select level
or
grade=Grade
So any rows that have any of the values above should be showed :
public List<Courses> getListCourseError() {
Courses courses = null;
List<Courses> coursesList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
courses = new Courses(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3), cursor.getInt(4), cursor.getString(5), cursor.getInt(6), cursor.getString(7), cursor.getInt(8), cursor.getInt(9));
coursesList.add(courses);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return coursesList;
}
Thanks
I believe that you issue is that string values have to be enclosed in quotes. You are also not including course_id is 0.
So instead of "SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade"
use :-
"SELECT * FROM COURSES WHERE course_id=0 OR semester_id=0 OR level_id=0 OR level_code='Select level' OR grade='Grade'"
However the above is a candidate for SQL injection so really you should be utilising the selection args (2nd parameter), which will properly enclose strings on your behalf. So the more correct solution would be to utilise :-
String[] selectionargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE course_id=? semester_id=? OR level_id=? OR level_code=? OR grade=?", selectionargs);
However, it is recommended to only use the rawQuery method when need and that the conveniece query method be used. This would be :-
String whereclause = "course_id=? OR semester_id=? OR level_id=? OR level_code=? or grade=?";
String[] whereargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.query(
"COURSES",
null, //<<<< all columns (else String[] of columns)
whereclause, //<<<< WHERE clause without the WHERE keyword
whereargs, //<<<< arguments to replace ?'s
null, //<<<< GROUP BY clause
null, //<<<< HAVING clause
null //<<<< ORDER BY clause
);
Notes
- null results in the respective parameter to be ignored/defaulted (table name cannot be null). e.g. columns (2nd parameter) as null defaults to ALL columns i.e. *.
there are a number of different query method signatures. See SQLiteDatabase
The code above is in-principle code and has not been tested so there may be some errors.

Storing SQL query output in an Array

I'm looking for a way to store the results/output of an SQL Query into an Array. I have a for loop which runs a query and each time the query is ran I would like to store the results in an array/arraylist. I tried using a cursor but I cannot store multiple strings in a cursor.
Here is the for loop:
for (int i=1;i<code.length;i++) {
Cursor cursor = myDataBase.query("codes", new String[]{"description"}, ("code = '" + code[i] + "'"), null, null, null, null);
cursor.moveToFirst();
String temp = cursor.getString(i);
result.add(i, temp);
cursor.close();
This doesn't seem to work.
Any suggestions or examples that could help?
Thanks
Assuming that code is a list of ids and the table name is named codes, and that you would like to retrieve the list of descriptions for all the codesTry you should this (using StringUtils.join from Apache commons):
String codes = StringUtils.join(code,",");
Cursor cursor = myDataBase.rawQuery("select description from codes where code in (?)",new String[]{codes});
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.add(cursor.getString(1));
}
cursor.close();

How to create filter

I have a database table with multiple columns
I use custom List<> and populate it from database
What i want to do is filter what will go into the list from database depending on user input
for example if i had a table like this:
name|phone|date|address
User can specify any filter(by name, by phone, by date... or all of it) and only items that matches all criteria will go into the list
Is there a way to do this?
Method that returns all items from database
public List<MoviesDatabaseEntry> getAllMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
MoviesDatabaseEntry list = new MoviesDatabaseEntry();
list.set_id(Integer.parseInt(cursor.getString(0)));
list.set_title(cursor.getString(1));
list.set_runtime(cursor.getString(2));
list.set_rating(cursor.getDouble(3));
list.set_genres(cursor.getString(4));
list.set_type(cursor.getString(5));
list.set_lang(cursor.getString(6));
list.set_poster(cursor.getString(7));
list.set_url(cursor.getString(8));
list.set_director(cursor.getString(9));
list.set_actors(cursor.getString(10));
list.set_plot(cursor.getString(11));
list.set_year(cursor.getInt(12));
list.set_country(cursor.getString(13));
list.set_date(cursor.getInt(14));
// Adding to list
lists.add(list);
} while (cursor.moveToNext());
}
// return list
db.close();
cursor.close();
return lists;
}
You can filter the entries you get in the SQL query you are building in this line:
String selectQuery = "SELECT * FROM " + table;
To filter the dataset your retrieve, you would add a WHERE clause to it. When you would, for example, only want those entries where the rating is over 3, you would change this to:
String selectQuery = "SELECT * FROM " + table + " WHERE rating > 3";
SQL is a very powerful language which offers a lot of possibilities. It's an essential skill when you work with relational databases. When you want to learn it, I can recommend you the interactive tutorial website http://sqlzoo.net/
You have to change your database query for getting specific data from the query.
You have one function that returns all rows from database like so: getAllMovies(String table)
Here you are using:
String selectQuery = "SELECT * FROM " + table;
Make a new function like this:
public List<MoviesDatabaseEntry> getSelectedMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { <your row names> },
**check condition(as string)**, null,
null, null, null, null);
...
}
Now just call this function when required with your specific query string
Make as many functions as you want!

Android: SQL rawQuery with wildcard (%)

I'm having a rawQuery() with following sql string similar to this:
selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
but now I have to include a wildcard in my search, so my query looks something like this:
SELECT column FROM table WHERE column LIKE 'searchstring%'
But when the query contains single quotes the following SQLite Exception is thrown: android.database.sqlite.SQLiteException: bind or column index out of range
How can I run a rawQuery with selectionArgs inside a SQL query with wildcard elements?
You have to append the % to the selectionArgs itself:
selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
Note: Accordingly % and _ in the searchString string still work as wildcards!
The Sqlite framework automatically puts single-quotes around the ? character internally.
String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);
That's it.
Brad Hein's and Mannaz's solution did not work for me, but this did:
String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);

Categories