Android中如何使用SQLiteStatement向SQLite插入当前DateTime时间
解决方案
SQLite本身没有原生的DATETIME存储类型,你有两种实现方式可选:
方案1:利用表定义的默认值(推荐)
你在建表时已经给date_insert字段设置了DEFAULT CURRENT_TIMESTAMP默认值,插入数据时只要不显式给该字段赋值,SQLite会自动填充当前时间,完全不需要手动处理日期逻辑,修改代码如下即可:
public void insertScannedCashCard(String scannedCashCard,byte[] cc_image){ try { SQLiteDatabase database = getWritableDatabase(); // 显式指定插入的字段列表,跳过date_insert字段,自动用默认值 String sql = "INSERT INTO CgList(cash_card_actual_no, hh_number, series_number, cc_image, id_image, cash_card_scanned_no, card_scanning_status) VALUES (?,?,?,?,?,?,?)"; SQLiteStatement statement = database.compileStatement(sql); statement.clearBindings(); statement.bindString(1, ""); statement.bindString(2, ""); statement.bindString(3, ""); statement.bindBlob(4, cc_image); statement.bindString(5,""); statement.bindString(6, scannedCashCard); statement.bindString(7, "0"); // 对应card_scanning_status字段 statement.executeInsert(); } catch(Exception e){ Log.v(TAG,e.toString()); } }
方案2:手动绑定日期
如果需要自定义插入的时间,直接按字符串类型绑定即可,SQLite支持识别yyyy-MM-dd HH:mm:ss格式的字符串作为日期值,没有单独的bindDate类方法,正确写法如下:
public void insertScannedCashCard(String scannedCashCard,byte[] cc_image){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strDate = sdf.format(new Date()); try { SQLiteDatabase database = getWritableDatabase(); String sql = "INSERT INTO CgList VALUES (NULL,?,?,?,?,?,?,0,?)"; SQLiteStatement statement = database.compileStatement(sql); statement.clearBindings(); statement.bindString(1, ""); statement.bindString(2, ""); statement.bindString(3, ""); statement.bindBlob(4, cc_image); statement.bindString(5,""); statement.bindString(6, scannedCashCard); // 直接用bindString绑定格式化后的日期字符串即可 statement.bindString(7, strDate); statement.executeInsert(); } catch(Exception e){ Log.v(TAG,e.toString()); } }
你也可以选择用时间戳(Long类型)存储日期,绑定的时候调用bindLong方法传入毫秒值即可,后续查询时再转换成日期格式。
内容的提问来源于stack exchange,提问作者CarlJade
相关产品推荐
相关产品推荐

