如何在 Android 应用程序中插入日期时间设置为“现在"的 SQLite 记录? [英] How to insert a SQLite record with a datetime set to 'now' in Android application?

查看:32
本文介绍了如何在 Android 应用程序中插入日期时间设置为“现在"的 SQLite 记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们创建了一个表:

Say, we have a table created as:

create table notes (_id integer primary key autoincrement, created_date date)

要插入记录,我会使用

To insert a record, I'd use

ContentValues initialValues = new ContentValues(); 
initialValues.put("date_created", "");
long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);

但是如何将 date_created 列设置为now?为了清楚起见,

But how to set the date_created column to now? To make it clear, the

initialValues.put("date_created", "datetime('now')");

不是正确的解决方案.它只是将列设置为datetime('now')"文本.

Is not the right solution. It just sets the column to "datetime('now')" text.

推荐答案

不能通过 Java 包装器ContentValues"使用 datetime 函数.您可以使用:

You cannot use the datetime function using the Java wrapper "ContentValues". Either you can use :

  • SQLiteDatabase.execSQL 以便您可以输入原始 SQL 查询.

  • SQLiteDatabase.execSQL so you can enter a raw SQL query.

mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");

  • 或者java日期时间功能:

  • Or the java date time capabilities :

    // set the format to sql date time
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    Date date = new Date();
    ContentValues initialValues = new ContentValues(); 
    initialValues.put("date_created", dateFormat.format(date));
    long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);
    

  • 这篇关于如何在 Android 应用程序中插入日期时间设置为“现在"的 SQLite 记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆