I have this SQL.
select sum(distance) AS distance FROM RoadTravelTableFile where checkBoxBusiness ='1' and plate_Number = 'AAA567'"
I have seen this simple query for raw sql in the Ormlite document.
long maxUnits = orderDao.queryRawValue("select max(units) from orders");
With that example, I coded my sql like this and it works.
distance = (int) getHelper().getRoadTravelTableFileIntegerDao().queryRawValue("SELECT SUM(distance) FROM RoadTravelTableFile where checkBoxBusiness = '1' and plate_Number ='AAA567' ");
But I have a problem, How can you make the checkBoxBusiness and plate_Number value as a parameter?
Replace current values with ? and add arguments to the queryRawValue method.
Integer checkBoxBusiness = 1;
String plateNumber = "AAA567";
distance = (int) getHelper()
.getRoadTravelTableFileIntegerDao()
.queryRawValue("SELECT SUM(distance) FROM RoadTravelTableFile where checkBoxBusiness = ? and plate_Number = ?", checkBoxBusiness, plateNumber);
Related
So I've got the following queries:
//returns min max value my odomoter field must have
#Query("SELECT MAX(odometer) FROM MaintenanceRecord WHERE vehicleId = :maintenanceVehicleId AND " +
"maintenanceTs < :dateAsLong")
Maybe<Float> getMinAllowedOdometer(long dateAsLong, int maintenanceVehicleId);
//returns the max value my odometer field is allowed to have
#Query("SELECT MIN(odometer) FROM MaintenanceRecord WHERE vehicleId = :maintenanceVehicleId AND " +
"CAST(strftime('%s',DATE(maintenanceTs/1000,'unixepoch')) AS integer) > " +
"CAST(strftime('%s',DATE(:dateAsLong/1000,'unixepoch')) AS integer)")
Maybe<Float> getMaxAllowedOdometer(long dateAsLong,int maintenanceVehicleId);
One function returns the min value the odometer column must have, and the other query returns the max value the odometer column is allowed to have.
The issue is that BOTH functions are executed after each other since I need to subscribe to both functions. That's bad practice, In my honest opinion.
Can I put these two queries in one query and return Maybe<Float, Float> as a result?
My other solution would be running these functions synchronously; instead of Maybe<Float>, I would directly return Float.
You can use conditional aggregation to get both columns in a single query:
SELECT MAX(CASE WHEN maintenanceTs < :dateAsLong THEN odometer END) AS max_odometer,
MIN(CASE WHEN CAST(strftime('%s', DATE(maintenanceTs / 1000, 'unixepoch')) AS INTEGER) > CAST(strftime('%s', DATE(:dateAsLong / 1000,'unixepoch')) AS INTEGER) THEN odometer END) AS min_odometer
FROM MaintenanceRecord
WHERE vehicleId = :maintenanceVehicleId;
This is the structure and data of my table funco inside database your.db (SQLite):
Id Disp Tp
1 Ball 2
2 Light 1
3 Sea 4
This is my code:
var db = SQLiteDatabase.openDatabase(this.filesDir.path +
"/your.db",null, SQLiteDatabase.OPEN_READWRITE)
val c = db.rawQuery("Select Id, Disp, Tp From Funco Where Id<=2;",null)
var stat = c.moveToFirst()
var result=""
while (stat) {
val mId = c.getInt(c.getColumnIndex("Id"))
val mDisp = c.getString(c.getColumnIndex("Disp"))
val mTp = c.getInt(c.getColumnIndex("Tp"))
result += "$mId $mDisp $mTp | "
stat = c.moveToNext()
}
c.close()
db.close()
The result value:
1 Ball 2 | 2 Light 1 |
If I replace my second line for
val c = db.rawQuery("Select ?, ?, ? From Funco Where ?<=2;"
,arrayOf("Id","Disp","Tp","Id"))
There is no error raised, but the cursor is empty!
Why?
Update:
The #tynn answer is right. I think that the documentation is subtle.
I think that compiler shoud be throw an error and not just return empty cursor.
In the same flavor, one can write
val c = db.query("funco",arrayOf("Id","Disp","Tp"),"Id<=?",
arrayOf("2"),null,null,null)
But below code fails
val c = db.query("funco",arrayOf("Id","Disp","Tp"),"?<=?",
arrayOf("id","2"),null,null,null)
As the documentation states:
selectionArgs String: You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
The question marks are there to bind different values to a precompiled SQL query. This functionality is not suitable for configuring the columns to be used in the query. Your first approach is the correct one. You could make the 2 in it dynamic though:
db.rawQuery("Select Id, Disp, Tp From Funco Where Id<=?;", arrayOf("2"))
My query is:
String _query = "select DISTINCT Y.CATE_CODE4 CATE_CODE, Y.CATE_NAME4 CATE_NAME,
0 IS_PRESET from G_MASTER X INNER JOIN CATEGORY_VIEW Y ON X.CATE_4 = Y.CATE_CODE4
where X.IS_SALE = 1 AND Y.IS_LOCKED4 = 0 AND Y.CATE_NAME2 not in ('XXXX')";
How does Android SQLite make db.query()?
First of all you should read SQLiteDatabase reference.
You could use a rawQuery(), here's an example of it :
rawQuery - db.rawQuery("select DISTINCT Y.CATE_CODE4 CATE_CODE, Y.CATE_NAME4 CATE_NAME,
0 IS_PRESETG_MASTER X INNER JOIN CATEGORY_VIEW Y ON X.CATE_4 = Y.CATE_CODE4 from table where X.IS_SALE = 1 AND Y.IS_LOCKED4 = 0 AND Y.CATE_NAME2 not in ('XXXX')"",new String[]{"data"});
It's just an example, you have to adapt your code to this.
How do I add quotation around string variable any idea? my database execute query if "" is around variable name what do I do ? I did this"+"+ School_name+"+"but its not working how I add variable name with quotation ?
Bundle bundle = this.getIntent().getExtras();
School_name = bundle.getString("Serachvalue");
db.selectQuery("SELECT * FROM uss_school sch LEFT JOIN uss_school_to_level sl ON
sch.school_id = sl.school_id LEFT JOIN uss_level l ON sl.level_id = l.level_id WHERE
l.title ="+ School_name+" ORDER BY sch.name ASC");
But data base execute wuery with in quotes,
SELECT * FROM uss_school sch LEFT JOIN uss_school_to_level sl ON sch.school_id =
sl.school_id LEFT JOIN uss_level l ON sl.level_id
= l.level_id WHERE l.title = "Elementary" ORDER BY sch.name ASC
Try following way,
db.selectQuery("SELECT * FROM uss_school sch LEFT JOIN uss_school_to_level sl ON
sch.school_id = sl.school_id LEFT JOIN uss_level l ON sl.level_id = l.level_id WHERE
l.title ='"+ School_name+"' ORDER BY sch.name ASC");
You simply need to add ' whenever you are using string variable in query field.
i need to create a function for sqlite, because the sin and cos mysql-function doesn't exist, and i need to make a query like:
String q = "SELECT * FROM shops WHERE _id > 0 AND distance(lat, lng, latitudine, longitudine) < 20 AND cancellato=0 ORDER BY _id";
Cursor c = myDataBase.rawQuery(q, null);
return c;
so, i need a function for distance.
and i can't do it via code because it's a list of +8000 shops!
how can i? i didn't found anything on the web.
thanks!
distance(lat, lng, latitudine, longitudine)
I think you have to calculate distance pragmatically from your javacode then you can compare
http://www.sqlite.org/lang_aggfunc.html
http://oreilly.com/catalog/sqlnut/chapter/ch04.html