有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从SQLite Android Studio java检索日期

我将当前日期保存在SQLite中,然后从SQLite中检索日期,但每次结果为零,问题出在哪里

我获取当前日期的代码是

 private String getDate() {

        Calendar calendar = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("dd / MM / yyy ");
        return mdformat.format(calendar.getTime());
 }

我的代码保存到SQLite中

           PrayDBHelper mDBHelper = new PrayDBHelper(PrayActivity.this);
           SQLiteDatabase db = mDBHelper.getWritableDatabase();

           db.execSQL("INSERT INTO " + prayEntry.TABLE_NAME + " " +prayEntry.DATE +  " VALUES " +
                     getDate());

我要从SQLite数据库检索的代码

    dbConnection();
    Cursor cursor= db.query(prayEntry.TABLE_NAME,prayEntry.DATE,null,null, null,
            null,null);
    while (cursor.moveToNext()) {
        String date = (cursor.getString(0));// get Date
        labelDATE.setText(date);
    }

共 (2) 个答案

  1. # 1 楼答案

    我认为您提出的是INSERT,因为表名后面的值、要放入数据的列应该在括号内。此外,值本身应该在括号内,值内的字符串应该用单引号括起来,所以

    db.execSQL("INSERT INTO " + prayEntry.TABLE_NAME + " " +prayEntry.DATE +  " VALUES " +
                     getDate());
    

    你应该使用:-

    db.execSQL("INSERT INTO " + prayEntry.TABLE_NAME + "(" +prayEntry.DATE +  ") VALUES ('" +
                     getDate() + "'));
    

    如果您使用insert便利方法,这将代表您构建正确的SQL。因此,建议您使用:-

    PrayDBHelper mDBHelper = new PrayDBHelper(PrayActivity.this);
    SQLiteDatabase db = mDBHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(prayEntry.DATE,getDate());
    db.insert(prayEntry.TABLE_NAME,null,cv);
    

    同样值得注意的是,在检索数据时不直接使用列偏移量,而是使用游标的getColumnIndex方法来获取偏移量

    因此,您可以使用以下选项来代替String date = (cursor.getString(0));

    String date = (cursor.getString(cursor.getColumnIndex(prayEntry.DATE)));
    

    关于日期,如果您以SQlite认可的格式存储日期,例如YYYY-MM-DD(2019-01-01,2019年1月1日),您可能会发现,这种格式的日期可以直接排序,并允许SQlite的日期和时间函数直接使用。因此,建议您使用SimpleDateFormat("yyyy-MM-dd")

  2. # 2 楼答案

    永远不要在SQLite中以不同于YYYY-MM-DD的格式存储日期
    在按此日期进行查询、比较和排序时,除此格式之外的任何内容都会给您带来麻烦
    对于您的代码,以下语句(包括必须存在于代码中的列名周围的括号,否则将抛出异常,所以我猜这只是一个输入错误):

    "INSERT INTO "+prayEntry.TABLE_NAME+" ("+prayEntry.DATE +") VALUES "+getDate()
    

    将在表中保存0,因为getDate()返回一个类似于:19 / 12 / 2019的值,该值被解释为数字19、12和2019之间的整数除法,结果为0
    原因是您没有将日期括在单引号内,例如:

    "INSERT INTO "+prayEntry.TABLE_NAME+" ("+prayEntry.DATE +") VALUES '"+getDate()+"'"
    

    但这不是推荐的插入方式
    使用insert()ContentValues()方法如下:

    PrayDBHelper mDBHelper = new PrayDBHelper(PrayActivity.this);
    SQLiteDatabase db = mDBHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(prayEntry.DATE, getDate());
    db.insert(prayEntry.TABLE_NAME, cv);
    db.close();