Inserting current date and time in SQLite database - sqlite

I want to create a table in SQLite in which one of the field is for date, in which date and time of current instance should save. Which data type should I use?
I'm planning to use 'timestamp'. How to insert current timestamp value to the field? Also how to write content values for this date field?

SQLite supports the standard SQL variables CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP:
INSERT INTO Date (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
The default data type for dates/times in SQLite is TEXT.
ContentValues do not allow to use generic SQL expressions, only fixed values, so you have to read the current time in Java:
cv.put("LastModifiedTime",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

INSERT INTO Date (LastModifiedTime) VALUES(DateTime('now'))
Use this site for further reference.

To get the current local(system) time, add the 'localtime' option:
select datetime('now', 'localtime');

I'm using timestamps a lot in my app. For me the best way to keep the timestamp is to convert it in milliseconds. After that it is easy to convert it to any locale.
If you need the current time use System.currentTimeMillis().
Content values are easy to use, you just and field and value, like:
ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());

Since SQLite 3.38.0, there is a unixepoch() function that returns UNIX timestamp in integer. Does the same thing as strftime('%s').
References:
release log draft
check-in

In my case i wanted to have a timestamp with fractions of a second.
The keyword CURRENT_TIMESTAMP has only a precision of YYYY-MM-DD HH:MM:SS (see docs DEFAULT clause).
The function strftime() can return fractions of a second
Example to use strftime() in an INSERT
INSERT INTO YourTable (TimeStamp)
VALUES (strftime('%Y-%m-%d %H:%M:%S:%s'))
Comparison of CURRENT_TIMESTAMP and strftime()
SELECT 'CURRENT_TIMESTAMP' as Timestamp_Command,
CURRENT_TIMESTAMP as TimeStamp_Precision,
'only seconds' as Timestamp_Comment
UNION ALL
SELECT 'strftime(%Y-%m-%d %H:%M:%S:%s)' as Timestamp_Command,
(strftime('%Y-%m-%d %H:%M:%S:%s')) as TimeStamp_Precision,
'with fraction of a second' as Timestamp_Comment
Example to use it in c#
The following is based on bulk insert in sqlite with ado.net
public static void InsertBulk(SqliteConnection connection)
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var command = connection.CreateCommand();
command.CommandText =
#"INSERT INTO BulkInsertTable (CreatedOn, TimeStamp)
VALUES ($createdOn, strftime('%Y-%m-%d %H:%M:%S:%s'))";
var parameter3 = command.CreateParameter();
parameter3.ParameterName = "$createdOn";
command.Parameters.Add(parameter3);
// Insert a lot of data
// calling System.DateTime.Now outside the loop is faster
var universalTime = System.DateTime.Now.ToUniversalTime();
for (var i = 0; i < 15_000; i++)
{
parameter3.Value = System.DateTime.Now.ToUniversalTime();
// faster
// parameter3.Value = universalTime;
command.ExecuteNonQuery();
}
transaction.Commit();
}
connection.Close();
}

Related

LINQ to SQL - Combine date and time columns into a single value

I'm trying to translate this SQL statement to LINQ:
SELECT sessionid, userid, CAST(sessiondate AS DATETIME) + CAST(sessiontime AS DATETIME) AS sessiondatetime FROM sometable
where sessiondate is of type DATE and sessiontime is of type TIME.
I've tried the following:
var query = from session in table
select new
{
session.Id,
session.UserId,
DateTime = session.Date + session.Time
};
where table is the return value of a GetTable<Session>() call on a DataContext instance and the Session class maps sessionid to Id, userid to UserId, sessiondate to Date (DateTime), and sessiontime to Time (TimeSpan).
The LINQ gets translated to this rather lengthy SQL statement:
SELECT [t0].[sessionid] AS [Id], [t0].[userid] AS [UserId], CONVERT(DateTime,DATEADD(HOUR, DATEPART(HOUR, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(MINUTE, DATEPART(MINUTE, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(SECOND, DATEPART(SECOND, [t0].[sessiontime]), CONVERT(DateTime,DATEADD(MILLISECOND, DATEPART(MILLISECOND, [t0].[sessiontime]), [t0].[sessiondate])))))))) AS [DateTime] FROM [sometable] AS [t0]
Unfortunately, when attempting to execute that statement, it tells me that "The datepart millisecond is not supported by date function dateadd for data type date." I'm guessing it's unhappy about the DATEADD call with milliseconds. Is there a way to fix this?
Edit: note that both session.Date and session.Time are nullable.
That unfortunate data structure makes the code unfortunately ugly:
var query = from session in table
select new
{
session.id,
session.userid,
combinedDate = new DateTime(
session.Date.Year, session.Date.Month, session.Date.Day,
session.Time.Hour, session.Time.Minute, session.Time.Second,
session.Time.Millisecond)
};

Android SQLITE Insert into table with values coming from a subquery

In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.
The insert into statement may look like the following example:
INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
At present I am doing it manually building the query:
String MyQuery = "INSERT INTO mytable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String
SQLiteDatabase= db = getWritableDatabase();
db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
What i would like to do instead is:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));
db.insert("MyTable", null, values);
db.close();
Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.
Is there a way to achieve this?
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands.
It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().

SQL query using date() function

This is OrientDb 2.1.4.
The following query works fine:
select from SyncableHist where history_date <= date('2016-04-12 21:25:17','yyyy-MM-dd HH:mm:ss')
and returns as expected three records and each records has the value of history_date = '2016-04-12 21:25:17'. The history_date is a DATETIME type.
However this does not return any records:
select from SyncableHist where history_date = date('2016-04-12 21:25:17','yyyy-MM-dd HH:mm:ss')
Any ideas???
Thanks!
Format your date to string before compare. Not sure why, but probably have something extra like miliseconds or your database can't compare both this way.
select from SyncableHist where history_date.format('yyyy-MM-dd HH:mm:ss') = '2016-04-12 21:25:17'

Compare date part of datetime column with NamedQuery

I have a table containing entries with date and time. I try to create a NamedQuery which only compares the date part.
#NamedQuery(name = "Vote.findForDate", query = "SELECT v FROM Vote v WHERE v.createdAt = :date")
...
createNamedQuery("Vote.findForDate").setParameter("date", date, TemporalType.DATE).getResultList();
But it seems that it always tries to compare the whole datetime.
Is there no way without using date() function in SQL?
I try to be independent from the database. For example h2 has no date() function.
One possible solution is the usage of date as column type and reduce the information.
#Column(name = "voteDate")
#Temporal(value = TemporalType.DATE)
private Date voteDate;

Using dates with Cassandra

I've just started my adventure with Cassandra database. I've managed to learn some basics but what I still can't understand is how to work with dates in Cassandra?
So for example in MySQL we have a datetime type for a field and we can query (for example) all fields with creation date less then 2010-01-01. Furthermore we can order the result by creation date field.
How can we achieve the same with Cassandra? How to define the corresponding Column Family and how to query (CQL) it to get the same result?
You can use type DateType to define a column of type DateType in your column family. You should really read this page, it has description and example how to do range query (that is creationdate < 2010-01-01). For ordering, you can refer to the SliceRange but this will probably cover in the cassandra client already. You will probably want to look into the cassandra client to do the query.
This is a snippet on how to do query in cassandra using hector client.
// 2010-01-01
Date date = new Date(1262275200L);
try
{
getConnection();
IndexedSlicesQuery<String, String, String> indexedSlicesQuery = HFactory.createIndexedSlicesQuery(keyspace, ss, ss, ss);
indexedSlicesQuery.setColumnNames("name");
indexedSlicesQuery.addLtExpression("timestamp", ByteBufferUtil.string(date_s.toByteBuffer(date)));
indexedSlicesQuery.addEqualsExpression("searchall", ByteBufferUtil.string(bs.toByteBuffer(true)));
indexedSlicesQuery.setColumnFamily(column_family);
indexedSlicesQuery.setStartKey("");
System.out.println(indexedSlicesQuery.toString());
QueryResult<OrderedRows<String, String, String>> res = indexedSlicesQuery.execute();
List<Row<String, String, String>> list = res.get().getList();
for (Row<?, ?, ?> row : list)
{
System.out.println(row.getKey());
}
}

Resources