I've accidentally inserted the string datetime() into my database (in stead of the result of the function), and never saw my mistake until i did a listing of the data. The string "datetime()" is in the date field of all the records, yet the field type is datetime!
Is this normal for the sqllite that is on Android?? What's the point of field types then?
Yes, sqlite isn't strongly statically typed like most databases. When you assign a type to a column, it's more like a suggestion about how you'd want the value stored. If you create a column which is a text column, it will store numbers you put there as strings, since it can convert a number to a string for you. If you create a column with a integer type and try to store a string in it, it stores a string if it can't be converted to an integer. Read more about it here
Related
I've text type column named 'amountDesc' having some values in it. I want to get all values which have values greater than 100. I wrote a query but it's not giving the correct result.
Database as you can see as under.
i've tried this code:
String query = "SELECT amountDesc FROM increment WHERE amountDesc > 100";
Cursor rawQuery = getReadableDatabase().rawQuery(query, null);
if (rawQuery.moveToFirst()) {
while (!rawQuery.isAfterLast()) {
String value = rawQuery.getString(rawQuery.getColumnIndex("amountDesc"));
rawQuery.moveToNext();
Log.d("tvlateamoutn1", value);
}
}
and getting these values on Logcat:
500 50 200 50
as you can see its not correct values as I required > 100 values. I know its question of for most beginners level but I stuck in it. Kindly resolve.
I've text type column named 'amountDesc' having some values in it.
So in your table definition you have amountDesc TEXT or something equivalent?
From the documentation:
A column with TEXT affinity stores all data using storage classes NULL, TEXT or BLOB. If numerical data is inserted into a column with TEXT affinity it is converted into text form before being stored.
and:
If one operand has TEXT affinity and the other has no affinity, then TEXT affinity is applied to the other operand.
Since the column has text affinity, the other operand is being converted from the integer 100 to the string '100'. The string '50' is greater than the string '100' because '5' is greater than '1'. Thus, your query is returning exactly what you're asking it to return. You're just asking it something different from what you think you are.
If you want to treat the values in that column as integers and compare them accordingly, use INTEGER not TEXT when creating the table. A poor workaround for not picking the correct affinity for the data stored in the column is to cast the values to the appropriate type when using them in calculations... CAST(amountDesc AS INTEGER) > 100 or something like that.
(Reading and understanding the linked documentation on datatypes and affinity is essential for using sqlite effectively.)
Can you check data type of amountDesc in schema. If declared data type is string, you can not compare with integer (100).
I'm trying to insert a special character values into my sqlite table. For that i have used following query, that contains octal values.
"INSERT INTO \"manufacturers\" VALUES(NULL,NULL,NULL,'1970-01-01 00:00:00','1970-01-01 00:00:00','35','A Priorite\\047');"
when i displaying the names it doesn't converted to corresponding string value, it displays the same octal value inserted as (A Priorite\047);
Now i need an suggestion to convert the octal value to string or char by using sqlite statements.
I know we can easily obtain it by using java code but my requirement is to do it by use of sqlite statements. Here the last value is the name field which is contains the octal value of \047(as string ').
I've also tried to convert the decimal value to char, it works fine. In my case, if i convert the octal value to decimal value then i can easily convert to char. but i can't convert octal to decimal.
Note: I'm having thousands of record, so can't manually insert the special characters into each row of table. And I'm not supposed to insert the values manually.
Thanks in Advance. Any help would be appreciated.
SQLite does not have octal escapes.
In Android, you should just use parameters to insert strings:
String sillyDate = "1970-01-01 00:00:00";
String someNumberAsString = "35";
String name = "A Priorite\047";
db.execSQL("INSERT INTO \"manufacturers\" VALUES(NULL,NULL,NULL,?,?,?,?)",
new Object[] { sillyDate, sillyDate, someNumberAsString, name });
If you really want to do this in SQL, you have to use a hexadecimal blob literal and convert that to text:
"INSERT INTO \"manufacturers\" VALUES(NULL,NULL,NULL,'1970-01-01 00:00:00',"+
"'1970-01-01 00:00:00','35','A Priorite' || x'27');"
Please note that in SQL, quotes inside strings can be escaped by doubling them:
"INSERT INTO \"manufacturers\" VALUES(NULL,NULL,NULL,'1970-01-01 00:00:00',"+
"'1970-01-01 00:00:00','35','A Priorite''');"
I resolved my problem. Now it's working cool. I just changed my insert query to below one.
"INSERT INTO \"manufacturers\" VALUES(NULL,NULL,NULL,'1970-01-01 00:00:00','1970-01-01 00:00:00','35','A Priorite\047'');"
Thanks to #LS_dev and #CL. I accept #CL's answer.
I try to delete from a table where there is a date field (represented as a string).
I'd like to do it by the following statement:
Object result=new Delete().from(Information.class).where("Date>=?", date.replace(".","-")).execute();
It seems that nothing was deleted, the result variable is null.
I have 2 questions:
How can I get the number of the deleted objects?
How can I use a where with a date variable?
The problem was on the object side, not the ActiveAndroid/SQLite side. SQLite can use dates for comparison but the source date has to be LocalDateTime. As you can see, I've been using Strings so the comparison gave false results.
Dont you have to add the (') char to a date?
Object result=new Delete().from(Information.class).where("Date>='?" + "'", date.replace(".","-") ).execute();
Like that?
I was curious if androids SQLiteDatabase insert method automatically handles type conversion.
Here is my example:
I have a csv file with a column name of age. Its type will be an INTEGER.
Lets say I have already created the database and table.
Now I am parsing the csv file with CSVReader, which parses each line and inserts each value into an index of a String[].
In order to insert each line of data into the database, I have to use a ContentValue object, which allows me to store values in it.
//Parse each line and store in line...
ContentValue values = new ContentValue();
values.put(KEY_AGE, line[1]); // Assume line[1] is the age
database.insert(table, null, values);
If I store the age value as a string (as seen above), and then insert it into the table, does Android handle the conversion to INTEGER before inserting it into the database?
I am asking this because I am trying to insert a bunch of tables into a database, and it looks much cleaner when I can just iterate through an array then explicitly state each put call, i.e:
Also if anyone has any design suggestions feel free to tell me.
CLEAN
int i = 0;
for(String s : TransitContract.Routes.COLUMN_ARRAY) {
values.put(s, line[i]);
i++;
}
UGLY
values.put(TransitContract.Routes.KEY_ROUTE_ID, line[0]);
values.put(TransitContract.Routes.KEY_AGENCY_ID, line[1]);
values.put(TransitContract.Routes.KEY_SHORT_NAME, line[2]);
values.put(TransitContract.Routes.KEY_LONG_NAME, line[3]);
values.put(TransitContract.Routes.KEY_DESCRIPTION, line[4]);
values.put(TransitContract.Routes.KEY_ROUTE_TYPE, Integer.parseInt(line[5]));
values.put(TransitContract.Routes.KEY_URL, line[6]);
values.put(TransitContract.Routes.KEY_COLOR, line[7]);
values.put(TransitContract.Routes.KEY_TEXT_COLOR, line[8]);
return mDatabase.insert(TransitContract.Routes.TABLE_NAME, null, values);
When you declare a column as INTEGER, SQLite will automatically convert strings to numbers, if possible.
See the documentation for Type Affinity.
If your ContentProvider doesn't restrict it (i.e. pass it directly to the SQLiteDatabase.insert() method), it should work. SQLite is not that picky about the types used in queries/inserts and the actual column type.
However, it would be best practice to parse and check the values before inserting. Otherwise you might actually insert a string which can't be parsed as integer and therefore retrieving the value might fail.
References:
Boolean datatype accepting string value and integer value
SQLite table with integer column stores string
I have an SQLite database within my Android application, which stores dates as integers. These integers are derived from a call to Java.util.Date.getTime();. I am trying to run a raw query of my database to get a Cursor to pass to a CursorAdapter and display in a ListView, but the date is stored as an integer as returned by getTime().
To keep my program simple, I would like to avoid using a SimpleArrayAdapter, and stick with the CursorAdapter.
Is it somehow possible to format the integer within the date colum as mm-dd-yyyy so that the column of the table, that the cursor is pointing to, contains properly formatted values rather than the integer that was returned by Java.util.Date.getTime(); when I added the item to the database?
SELECT strftime("%m-%d-%Y", date_col, 'unixepoch') AS date_col
Your code will work if it expects a result set column in that format called date_col.
EDIT: One thing you need to watch out for is that getTime uses milliseconds since 1970, while standard UNIX time (including SQLite) uses seconds.
The Java.util.Date.getTime(); method is returning an integer that represents the "unix time".
The simplest way to read this number as a date is by storing it as-is, and reading it using the following Sqlite query:
SELECT strftime('%m-%d-%Y', 1092941466, 'unixepoch');
which returns:
08-19-2004
If you need another format, you can use the strftime function to format is as you like, or any of the other date formats and functions available.
You'll have to, as Matthew Flaschen points out in a commend below, divide the date by 1000 before you are able to use them in this way. "Real" unix times are measured in seconds since the epoch, and Java.util.Date.getTime(); returns milliseconds since epoch.
SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.
Any value stored in the SQLite database has one of the following storage class:
NULL
INTEGER
REAL
TEXT
BLOB
so I am not sure what you meant by but the date is stored as a long, unhelpful integer.
For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.
I hope this helps.