Database problem (Android) - android

i'm trying to create a database with 4 columns(name,contact,date,mail) and i want to insert the values at a time with using array.
String[] name = {"raja","ravi", "ram"};
String[] contact = {"12345", "123457", "123478"};
String[] date = {"27 jul 2011", 28 Jul 2011"};
how to use this?

First see how to create a database and how to create table in the database.Forget about your string array.Once you can create,open database then see insert,delete,update,select operation.Proceed step by step.
Try to give some effort first and then ask people for the solution
Here is a nice example of creating a sqlite database and querying to the database.

Related

How to select unique month-year combinations from SQLite database using OrmLite?

I have a table with data and having a column with a date value.
Table A
table_id date
So think of the table as to have more than thousands of rows and entries. What I want to do is to select all the distinct months and years from the table, so the output would probably look something like this:
09 2013 09-2013
12 2014 12-2014
01 2015 01-2015
03 2015 03-2015
05 2015 05-2015
Maybe something like this? If this is possible?
dao.queryBuilder().distinct().selectColumns("strftime('%mm-%yyyy', date)").query();
But I can't seem to make the above work the way I want it to. My model also uses the DataType.DATE on its date field.
Is there some way I can use the distinct() method of OrmLite to return this kind of list? Any help would be greatly appreciated! Thank you!
SqlFiddleDemo
CREATE TABLE TableA(table_id INT, `date` DATE);
INSERT INTO TableA
VALUES (1, '2014-01-21'), (2, '2014-01-23'),
(3, '2015-01-21'), (4, '2015-01-01'), (5, '2014-07-21'), (6, '2012-01-01');
SELECT DISTINCT
STRFTIME('%m-%Y', t.`date`) AS Output
FROM TableA t
ORDER BY t.`date`;
I don't know OrmLite but I hope you manage to convert this solution or just use pure SQL with your ORM.
EDIT:
SELECT DISTINCT
STRFTIME('%m', t.`date`) AS Month,
STRFTIME('%Y', t.`date`) AS `Year`,
STRFTIME('%m-%Y', t.`date`) AS Output
FROM TableA t
ORDER BY t.`date`;
To be sure we are talking about the same thing : ORMLite is a "Object Relational Mapping Lite (ORM Lite) provides some simple, lightweight functionality for persisting Java objects to SQL databases [...]."
It's not a just a wrapper to some SQL raw queries : it provides a way to create models (some POJO) that will be persisted in a database, without having to handle SQL constraints and strong knowledge. You will be able to store objects and retrieve them using plain Java objects.
The selectColumns(String) method take a column name as argument. You are passing a raw SQL statement.
If you read the source code of this method, you have this :
public QueryBuilder<T, ID> selectColumns(String... columns) {
for (String column : columns) {
addSelectColumnToList(column);
}
return this;
}
and then
private void addSelectColumnToList(String columnName) {
verifyColumnName(columnName);
addSelectToList(ColumnNameOrRawSql.withColumnName(columnName));
}
and to finish :
/**
* Verify the columnName is valid and return its FieldType.
*
* #throws IllegalArgumentException
* if the column name is not valid.
*/
protected FieldType verifyColumnName(String columnName) {
return tableInfo.getFieldTypeByColumnName(columnName);
}
So, with introspection, ORMLite will try to find the given column name in the fields of your model. Your string is clearly NOT a column name :)
Also, for a more "conceptual" concern : I think you should not convert the date format from your request. Actually, ORMLite is in charge to persist models in your database. He is not designed to format your data correctly for processing or display. If after persisting data in the DB you need to display it another, you will have to make the "parse stuff" at this moment, not before.
To be summarize :
Use the real column name of the date field
Continue to use distinct() the way you do it
Parse the data to display it correctly if needed (let ORMLite choose the way it stores and load it)
Sources
http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_3.html#QueryBuilder-Capabilities
https://github.com/j256/ormlite-core/blob/master/src/main/java/com/j256/ormlite/stmt/QueryBuilder.java
https://github.com/j256/ormlite-core/blob/master/src/main/java/com/j256/ormlite/stmt/StatementBuilder.java

Android SQLite: How to update one column of all records with different values

I found on Stack similar questions like this How to update an entire column in sqlite? But they don't explain me my how to solve my task.
Say, I have a db with 5 columns and 5 records in it. What i need is to update the last column "date" with the values of unix time that differs by 1 sec. So i need to put values 1406820974139, 1406820974140, 1406820974141, 1406820974142, 1406820974143, 1406820974144.
How to do it using ContentValues? As i got i have to loop five times to create new ContentValues object and update one record at a time (maybe using db.startTransaction() syntax).
My question is is there a way to put all values at a time into one ContentValues object and write in them into DB? Or maybe the better way is to use rawQuery using native SQL syntax as explained in How to update an entire column in sqlite?
In theory, it would be possible to put all the values into a single SQL statement:
UPDATE MyTable
SET date = CASE _id
WHEN 5 THEN 1406820974139
WHEN 17 THEN 1406820974140
WHEN 23 THEN 1406820974141
WHEN 69 THEN 1406820974142
WHEN 666 THEN 1406820974143
END;
However, just creating one ContentValues object for each row is easier than constructing this command.
so that we know which date should go to which row? what is the cririteria to differentiate the rows?
a relational db table is different from say an excel table. there is no implicit row order (if you always see the rows in the same order,you can consider it a kind of coincidence,you can not rely on this like you do in excel), in a db table you need to have a column(or a group of them) with unique values which you use in your queries to identify each of your records.
so you need to be more clear in your question. what date should go to which record (identified by what?). there is no implicit row number, if you want it, add an autoincrement PK column.
then you could for instance use something along the lines of
UPDATE table SET column5= 1406820974140+PKcolumn
where 1406820974140 is the start date you have to choose, depending on what you are up to

Delete method is not working properly

I want to hold only last 22 minute data in my DB for that i used this
String[] str = null;
str = new String[]{"datetime('now','-22 minute')"};
databaseInstance.delete(table_n, "datetime(modified/1000,'unixepoch')<= ?", str);
In database our datatype of modified column is as below
"modified" DATETIME NOT NULL
But it deleting all data from DB that means either of before 22 minute or after 22 minute all data get deleted from our table. But i want to hold last 22 minute data in our table .Any help is really appreciated, Please someone take me out of this issue.Thanks in advance to all.
The while point of using parameters (?) is to avoid interpreting them, so that you are able to store strings containing quotes or function names in the database.
To execute the datetime function, it must be written directly into the SQL statement:
db.delete(table_n, "datetime(modified/1000,'unixepoch') <= datetime('now','-22 minute')", null);
Instead of converting the table value into the yyyy-mm-dd hh:mm:ss format, you could convert your comparison timestamp into the same format used in the table.
This would allow an index on the modified column (if any) to be used:
db.delete(table_n, "modified <= strftime('%s','now','-22 minutes')*1000", null);

Using select method in SQL

I've added 3 strings of data into a SQL database in android. A fourth string makes up the database, however it is a date:
SimpleDateFormat outputDate = new SimpleDateFormat(yyyy-MM-dd)
Date outputDate = new Date();
When the user enters information to the database, the adding method for the database creates the date, which is added to the database.
My question is, how can I use these imported dates to create a method whereby only the rows in the database that were added on in the last 31 days?
A SELECT method comes to mind through research, but I don't know how to implement it?
Thanks
Presuming your database engine is SQLite, you should try something like that
SELECT * from your_table where julianday('now') - julianday(your_date_field)<=31;
You may be interested in SQLite date functions as well: http://www.sqlite.org/lang_datefunc.html
As long as you ask about Android I assume that the database you use is SQLite. SQLite does not have datatype for date. Thus you have couple of options: store the date in string (like you did) or store the timestamp of the date.
I seriously recommend you to use the second option as it is going to convert your dates in integers and it will be even easier to handle.
Thus when you want to select only events in the last 31 days you can do:
SQLiteDatabase database = helper.getWriteableDatabase();
final long millisIn31Days = 31 * 24 * 60 * 60 * 1000;
String where = "<your-date-column> >= ?"
String [] whereArgs = { String.valueOf(new Date().getTime() - millisIn31Days) };
Cursor cursor =
database.query("<TABLE_NAME>", null, where, whereArgs, null, null, null);
Note that here I write in angular brackets all the values you should actually fill in with the correct constants.
If you, however, want to stick to the string solution, you can still go with string comparison, as long as you specify the date format in correct manner (yours seems to be like that). In the string solution you will need to calculate the date of 31 days ago. You can use the Calendar's class auxiliary methods to achieve that.

Deleting from android sqlite table

I have a column in android sqlite database table. The values in the column are like:
2011/06/01
2011/06/02
2011/06/05
2011/06/10
2011/06/11
2011/06/13
2011/06/15
2011/06/16
2011/06/25
2011/06/26
I have a string today="2011/06/27"
Now I want to delete those rows whose column value is older than 5 days from today.
How to modify the code to achieve this?
return db.delete(DATABASE_TABLE,where date="", null) > 0;
You have to store your dates in a other format, check the date function of SQLite. Use YYYY-MM-DD instead of YYYY/MM/DD. You already got an order on your dates defined by its string representation. So you can use the date function of SQLite to select the correct rows.
Dates older than 5 days would be queried like this.
... WHERE datecolumn < date('now', '-5 days') ...
There is no date type in sqllite
you just store a data represented value as a string or int
then use the date based functions of sqllite to get the values
You should be using the stored procedure rather than writing the service. It will make easier for your application to automatically update the records.
See link: http://searchoracle.techtarget.com/answer/Time-based-stored-procedure-to-check-table-and-update-old-records
Another solution is to use date instead of string. When you run your service then fetch data as Date and then you can make the simple comparison.

Categories

Resources