在sqlitedatabase中插入当前日期

时间:2014-04-09 03:22:29

标签: android

我有一个sqlitedatabase,我在其中插入当前日期。问题是,当我插入当前日期时,数据库中已有的日期也会更改为新日期。我想插入当前日期而不是更改以前插入的日期。请告诉我这里我做错了什么。感谢

 public static final String KEY_DATE = "current_date";

 @Override
 public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_DATE + " TEXT NOT NULL, " + 
        KEY_NAME + " TEXT NOT NULL);");
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // TODO Auto-generated method stub
     db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
     onCreate(db);
   }

   public MyDatabase(Context c){
        ourContext = c;
   }

   public MyDatabase open() throws SQLException {
       ourHelper = new DbHelper(ourContext);
       ourDatabase = ourHelper.getWritableDatabase();
       return this;
   }

   public void close(){
       ourHelper.close();
   }

  public long createEntry(String name) {
     SimpleDateFormat sdf = new SimpleDateFormat();
     Date mydate = new Date();
     ContentValues cv = new ContentValues();
     cv.put(KEY_DATE, sdf.format(mydate));
     cv.put(KEY_NAME , name);
     return ourDatabase.insert(DATABASE_TABLE, null, cv);
 }

//下面的代码显示了我如何从db

中读取
public String getData(){
            // TODO Auto-generated method stub

            String[] columns = new String[]{KEY_ROWID,KEY_DATE,KEY_NAME};
            Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
            String result =" ";

            int iRow = c.getColumnIndex(KEY_ROWID);
            int iDate = c.getColumnIndex(KEY_DATE);
            int iName = c.getColumnIndex(KEY_NAME);


            for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){

                result = result + c.getString(iRow) + " " + c.getString(iDate) + " " + c.getString(iName) + " " + "\n";     

            }

            return result;

         }

2 个答案:

答案 0 :(得分:0)

我认为不包含显示数据库版本的代码。

int version =1;
public Classname(Context applicationcontext) {
   super(applicationcontext, "databasename.db", null, version);

}

您还应该选择指定的日期格式

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

答案 1 :(得分:0)

我犯的错误是我之后添加了日期列。通过一次创建所有列,修复了问题。

Override


public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
    KEY_DATE + " TEXT NOT NULL, " + 
    KEY_NAME + " TEXT NOT NULL);");

}