I am using Ormlite in my Android project and I would like to know if it is possible to execute raw sql, for insertion for instance. I am not wanting to use QueryBuilder because I simply want to import a SQLite dump in my db the first time the app is launched.
Sure you can! From the Dao class you can just call executeRaw passing the query as a String. Something like:
this.getDao().executeRaw("UPDATE " + this.getTableName() + " SET number = " + String.valueOf(count) + " WHERE id = " + myId);
Related
Like said in the title I am trying to sort my data from sqlite database to ascending time. Here is what I have so far:
Cursor display = db.rawQuery("SELECT * FROM "+TableName + " ORDER BY Time ASC",null );
It displays data however it doesnt sort according to my Time with formade ##.## 24hr time. Hope someone can help.
Try "SELECT * FROM " + tableName + " ORDER BY time(Time)". PS: ASC is default ;)
You can use the strftime() function:
SELECT *
FROM my_table
ORDER BY strftime('%H:%M:%S',my_column)
Here I created a fiddle as example.
The raw query should be something like:
"SELECT * FROM " + TableName + " ORDER BY strftime('%H:%M:%S'," + my_column + ")"
NOTE: strftime() function is the more general function that you can use for manipulate date. But, for this specific case you can also use time(). Indeed, as the document that I linked says:
time(...) is equivalent to strftime('%H:%M:%S', ...)
I'm writing a function for an Android app, that should get the first 8 entries (names of cities) of a database which are matching a string.
This is my query:
Cursor cursor = database.rawQuery(
"SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE " + String.format("%s%%", nameLetters) +
" LIMIT " + 8
, null);
This is the resulting error:
android.database.sqlite.SQLiteException: near "LIMIT": syntax error (code 1): , while compiling: SELECT city_name FROM CITIES WHERE city_name LIKE berl% LIMIT 8
I have already checked out other questions on the platform, but could not find any solution helping me out. The database is tested and created correctly and also the search entry is in the database.
Could anybody help?
WARNING: You should NOT use string concatenation with the + operator to insert user input in a SQL query.This leaves your app open to a SQL injection attack. I cannot emphasize this enough. Mitigating this common security flaw should be a top priority for all database developers.
Instead, you should use the ? place holder syntax:
String query = "SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE ?" +
" LIMIT 8";
String[] args = {nameLetters + "%%"};
Cursor cursor = database.rawQuery(query, args);
Even if the database is small and only used for your individual app, it is best to make this syntax a habit. Then when you work on larger, more critical databases, you won't have to worry about this issue as much.
This also has the advantage that it quotes the input for you. You completely avoid the error which you encountered that prompted the original question.
For the sake of completeness I'll turn my comment into an answer, to hopefully help anyone else who may have this issue.
Think you need quotes around the like string eg
SELECT city_name FROM CITIES WHERE city_name LIKE 'berl%' LIMIT 8
Can someone create a greendao (or android sqllite) query to have the same result like the next sql query?
select b.*, a.MAIN_CATEGORY_ID from MAINCATEGORYS_TO_LISTINGS a
join APMAIN_CATEGORY b on b._id=a.MAIN_CATEGORY_ID where listing_id=10120
You could use the queryRaw() method in GreenDao.
If I understand what you are trying to do correctly, e.g.:
session.getMainCategoryDao().queryRaw(
" inner join " + MainCategoryToListingsDao.TABLENAME + " MCL "
+ " on T._id = MCL." + MainCategoryToListingsDao.Properties.MainCategoryId.columnName
+ " where MCL." + MainCategoryToListingsDao.Properties.ListingId.columnName
+ " = ?", listing.getId());
It's a little ugly, but should work. Of course you will have to modify based on how your DAOs are named and possibly how you named your properties. But when GreenDao names your primary table in the query, it is aliased by the T and the primary keys are _id
They rest you can pull by using the DAO's properties.
This will be supported in greenDAO 1.4, which will be released soon. If want you can build greenDAO from the "join" branch for an early version of it: https://github.com/greenrobot/greenDAO/tree/join
Is there a way of closing all cursors that have been used to query a certain database?
I DonĀ“t have the variable names, need a "close.all" sort of code.
Suppose you have some of these cursors, managed by external libraries (Parse Offline DataStore), not by your own code:
Cursor cursorvariablenames = database.rawQuery
("SELECT " + NAME + " FROM " + TABLE_NAME + " WHERE " + DAY_PERIOD[day_counter * 2]
+ " = '" + day + "' AND " + DAY_PERIOD[day_counter * 2 + 1] + " = "
+ Integer.toString(period), null);
I know the name of the sqlite DB = (ParseOfflineStore), and would like to close all cursors that are used by or point toward this DB.
I'll answer my own question to this: There's no solution at sight, no response from Parse team neither.
I am now using SharedPreferences file to handle local data to feed the widget. Any use of Parse Local Datastore will yield into cursor errors over time.
Hope this help someone experiencing the same problem while querying local sqlite databases from homescreen widgets and/or services.
You may try closing your DB withdb.close(); or dbHelper.close();, then all cursors operating on that database should be closed.
I know there is probably a simple thing I'm missing, but I've been beating my head against the wall for the past hour or two. I have a database for the Android application I'm currently working on (Android v1.6) and I just want to insert a single record into a database table. My code looks like the following:
//Save information to my table
sql = "INSERT INTO table1 (field1, field2, field3) " +
"VALUES (" + field_one + ", " + field_two + ")";
Log.v("Test Saving", sql);
myDataBase.rawQuery(sql, null);
the myDataBase variable is a SQLiteDatabase object that can select data fine from another table in the schema. The saving appears to work fine (no errors in LogCat) but when I copy the database from the device and open it in sqlite browser the new record isn't there. I also tried manually running the query in sqlite browser and that works fine. The table schema for table1 is _id, field1, field2, field3.
Any help would be greatly appreciated. Thanks!
Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES (" + field_one + ", " + field_two + ")";
although your schema contains three fields. By the way, you can see the log to see the actual error reporting from sqlite.
The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.
I thought it would be useful for others, not to have to dig through the comments to find the right answer.
Since it is a string values you forgot "'" to add...this query will surely work, i tested
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES ('" + field_one + "', '" + field_two + "')";
I changed my code to use myDataBase.insert() instead of rawQuery() and it's working. I'm not sure why the actual sql query didn't work though, so if anyone can shed some light on that I'd still appreciate it.