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', ...)
Related
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);
I have the following table:
String sqlStatement = "CREATE TABLE " + CallsEntry.TABLE_NAME + "(";
sqlStatement += CallsEntry.FIELD_CALL_ID + " INT PRIMARY KEY DESC,";
sqlStatement += CallsEntry.FIELD_CALLER_PHONE + " TEXT,";
sqlStatement += CallsEntry.FIELD_INSERTION_DATE_MILLIS + " INT); COMMIT;";
db.execSQL(sqlStatement);
Please note that the primary key is descending.
Then I expect from my experience with SQL server that the following query will yield the records in an descending order:
SELECT * FROM tblCalls;
However, this is not the case. I'm getting the records in ascending order. I have to use this:
SELECT * FROM tblCalls ORDER BY CallId DESC;
Why is that? Can I do something differently and get the records in descending order?
There is no such thing as default key order in SQLite.
Depends on documentation:
If a SELECT statement that returns more than one row does not have an
ORDER BY clause, the order in which the rows are returned is
undefined. Or, if a SELECT statement does have an ORDER BY clause,
then the list of expressions attached to the ORDER BY determine the
order in which rows are returned to the user.
So default order is underfined without ORDER BY clause.
Does this produce the right order?
SELECT CallId FROM tblCalls
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
I am currently implementing a search feature in an appliction to take a user input and query the database for similar results. I have created the following database query:
String proQuery = "SELECT * FROM " + DATABASE_TABLE + " WHERE "
+ KEY_NAME + " LIKE '%" + keyword +"%'";
Obviously this query has a number of limitations due to a very generic sql statement. For example, if I start typing something in the middle of the word, it will show up first in the list if it has a lower row number in the database.
Are there libraries that help make a more intelligent search feature than this very generic sql statement? I am not sure what keywords could describe this functionality what I'm looking for, is there some field of "search algorithms" for android?
Maybe UNION is what you're looking for:
SELECT * FROM (
SELECT * FROM table_name WHERE keyname LIKE 'keyword%' ORDER BY keyname
) alias_t1
UNION ALL
SELECT * FROM (
SELECT * FROM table_name WHERE keyname LIKE '%keyword%' AND keyname NOT LIKE 'keyword%' ORDER BY keyname
) alias_t2;
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.