To get multiple results of a query I use Cursor c = mydatabase.rawQuery("command", null); and then while (c.moveToNext()) { ... }. Works as advertised.
But if I just want to have one result as in SELECT rowSomething FROM table WHERE [row] = 'Test' and I know that it will be one result, a string, can I do something like
String result = mydatabase.StringQuery("Command");?
Yes, for example with DatabaseUtils#stringForQuery().
Related
I am using moveToFirst and it works very well. But this sql query doesnt work. I don't know why. I didn't receive any error.
My query
String sqlKomut = "SELECT SHareket.*,CHareket.[Meblag],Cari.AnlikBakiye FROM CHareket , SHareket,Cari WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '"+cari.getCariID()+"' AND SHareket.[Seri]='"+hareket.getSeri()+"' AND SHareket.[Sira]='"+hareket.getSira()+"'AND SHareket.[Tip]='"+hareket.getTip()+"' AND SHareket.[Cins]='"+hareket.getCins()+"' ORDER BY SHareket.[Satir]";
and I get my cursor getValue here:
Cursor cursor = db.rawQuery(sqlKomut, null);
if(cursor !=null){
if(cursor.moveToFirst()){
do {
eleman.setStrEleman(cursor.getString(cursor.getColumnIndex("Seri")));
eleman.setIntEleman1(cursor.getInt(cursor.getColumnIndex("Sira")));
eleman.setIntEleman2(cursor.getInt(cursor.getColumnIndex("CariID")));
eleman.setIntEleman10(cursor.getInt(cursor.getColumnIndex("Cins")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Tip")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Satir")));
eklenenfaturalar.add(eleman);
} while (cursor.moveToNext());
}
}
WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '...'
You cannot do multiple comparisons in a single expression like that.
(The comparison returns a boolean value, 0 or 1; any more comparisons will then use this boolean instead of an ID value, e.g., you end up with something like 1=Cari.CariID.)
To use multiple comparisons, connect them with AND (as you already did with the other ones):
WHERE CHareket.[CariID]=SHareket.[CariID]
AND SHareket.[CariID]=Cari.[CariID]
AND Cari.[CariID]='...'
...
Hello I am pretty new with SQLite and I am trying to deal with some database manipulation in my project.
I have a table with almost 4000 rows and this is the format of every row:
problem_id (string)
problem_no (string)
problem_title (string)
dacu (int)
I need to query a bunch of problem_no based on the problem_id. The quantity of query is almost 1000 at a time. So I wrote a query code like this:
Set<Integer> getProblemsTitle(HashSet<String> problemsIDs) {
SQLiteDatabase db = this.getReadableDatabase();
HashSet<Integer> problemNo = new HashSet<Integer>();
Cursor cursor = null;
for (Iterator<String> iterator = problemsIDs.iterator(); iterator.hasNext();) {
cursor = db.query(CommonUtils.PROBLEM_TABLE, new String[] {
CommonUtils.KEY_PROBLEM_NO },
CommonUtils.KEY_PROBLEM_ID + "=?",
new String[] { iterator.next() }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
problemNo.add(cursor.getInt(0));
}
cursor.close();
}
db.close();
Set<Integer> set = new TreeSet<Integer>(problemNo);
return set;
}
I know this is not a optimized snippet. And I need to optimize it a lot to reduce the execution time of the query. I did it inside AsyncTask but it is taking too much time.
How can I do this efficiently with faster performance?
You might want to consider taking this out of the database. If you just grabbed all the problems, you could add them all in code. Running one SELECT with 4000 results is still going to be much faster than a thousand SELECT statements.
The approach would be to grab them all, but sorted(ORDER BY problem_id). You could then just check each item in problemIDs against it, and add when you get a match.
You could also use the IN operator as Mathew suggests, but I don't know how efficient that will be with 1000 items in the set.
Don't iterate over a collection of IDs, but use the IN operator in a WHERE condition.
SELECT * FROM Table WHERE problem_id IN (1,2,3,4,5)
This will return all the records in the set. Whereas you are querying them one at a time.
You could try compiling a query, and maybe you can try to load the database into memory before reading.
Create an index on the problem_id column.
I have a rather big query that is returning data when executed outside android while returning nothing when executed within android.
I split the query in several pieces and determined that the union was ok.
I tried on a smaller set of data with the same behavior.
I've tested with different hardware and API versions.
I'm using the rawQuery method with constant values.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String, java.lang.String[])
This query was meant to replace a FULL OUTER JOIN which is not currently supported.
SELECT IFNULL(stype, gtype) AS type, IFNULL(sdate, gdate) AS date, IFNULL(sroute, groute) AS route FROM (
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM Sensor_Point AS sp LEFT JOIN GPS_Point AS gp ON gp._id IS NULL AND sp.sent=0 AND sp.route=gp.route AND sp.route=1
UNION ALL
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM GPS_Point AS gp LEFT JOIN Sensor_Point AS sp ON sp._id IS NULL AND gp.sent=0 AND sp.route=gp.route AND gp.route=1
) WHERE route=1 ORDER BY date ASC LIMIT 255
Any hints would be greatly appreciated.
Update:
Look's like the problem is finally with the query parameters, if I set it this way:
String[] args = new String[3];
args[0] = args[1] = args[2] = "1";
Cursor data dataBase.rawQuery(SELECT_POINTS, args);
It doesn't work, while it works when hardcoding values directly in the query.
Cursor data = dataBase.rawQuery(SELECT_POINTS, null);
In the Android database API, all query parameters are strings.
(This is a horrible design mistake.)
Your query corresponds to:
... AND sp.route='1'
Try to convert the parameter strings back into a number like this:
... AND sp.route = CAST(? AS INT)
or just put the number directly into the query string.
Right now my code looks like this:
Cursor cursor = getContentResolver().query(messagesUri, null,"address=?", smsNo, null);
where smsNo is a singleton array.
I would like to add elements to this array and implement an OR operation in the WHERE clause. Is this possible to do continuing to use an array?
I'm not quite sure what you're asking, but you certainly can continue to use an array here. If you're asking how to extend an existing array to have more items, you can use Arrays.copyOf(oldArray, newSize) to make additional space in it. And you can then just use multiple ? placeholders in your query string to reference the new items.
For example:
queryParameters = Arrays.copyOf(smsNo, 2);
queryParameters[1] = "another number"
Cursor cursor = getContentResolver().query(messagesUri, null,"address=? or address=?", queryParameters, null);
This is my first time using a database and I'm not really sure how this works. I made the database and made a query that returns a cursor and... now what? What is a cursor, really? Can I just use that to navigate through my data or do I have to put it in an ArrayList or ListActivity or what?
You need to iterate the cursor to get your results.
Use cursor.moveToFirst() and/or cursor.moveToNext() (with a while loop). Then you can use the getX() method, like cursor.getInt() or cursor.getString().
For example, ir your are expecting one result from your query:
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex('NAME'));
int age = cursor.getInt(cursor.getColumnIndex('AGE'));
} else {
// oops nothing found!
}
First call cursor.moveToFirst(). Each time you call cursor.moveToNext() it will move to the next row. Make sure when you are done with your cursor you call cursor.deactivate() or you will get errors in your log cat.
Iterate over the returned Cursor instance
public List<Object[]> cursorToTableRows(Cursor cursor) {
List<Object[]> result = new ArrayList<Object[]>(cursor.getCount());
cursor.move(0);
cursor.moveToNext();
while (cursor.isAfterLast() == false) {
Object[] tableRow = new Object[cursor.getColumnCount()];
for(int i=0; i<cursor.getColumnNames().length; i++) {
int columnIndex = cursor.getColumnIndex(cursor.getColumnName(i));
String columnValue = cursor.getString(columnIndex);
tableRow[i] = columnValue;
}
result.add(tableRow);
cursor.moveToNext();
}
cursor.close();
return result;
}
Then create the desired objects.
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Cursor cursor = null;
List<Object[]> objects = cursorToTableRows(cursor);
for(Object[] row : objects) {
int i=0;
Vehicle vehicle = new Vehicle(row[i++].toString(), row[i++].toString()));
vehicles.add(vehicle)
}
return vehicles;
}
from Developer.android: This interface provides random read-write access to the result set returned by a database query.
In other words: query returns you a set of data represented by a cursor. First you need to make sure you got a valid cursor (not null) and then try to move it to desired position in the data set (use moveToXXX methods). In order to obtain data pointed by cursor use getXXX methods. When done using it make sure to call close to release resources.
According to this link it looks like you can iterate through the query return using something like:
cursor.next();
And grab the data at the location you are looking for using:
cursor.getString(0)
After you successfully have your Cursor setup, you would typically want to display that to a view in some form.
Have a look at the following answer for a detailed, but simple example of using a Cursor Adapter to pair up your newly-minted Cursor with your desired XML View:
https://stackoverflow.com/a/20532937/293280