SQLite:在数据库中添加日期列

时间:2014-07-02 20:38:15

标签: android mysql sql database sqlite

在我当前的应用程序中,有一个SQLite数据库正在按预期运行。但是我想在数据库中添加一个日期列。

如何将此列添加到下面的DatabaseHelper类中?

DatabaseHelper类:

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "MultapplyDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "scores";

    // Contacts Table Columns names
    private static final String COL_NAME = "name";
    private static final String COL_SCORE = "score";



    /**
     * Constructor
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "("
                + COL_NAME + " STRING PRIMARY KEY," + COL_SCORE + " INTEGER" + ")";
        db.execSQL(CREATE_TABLE_SCORE);


    }

    /**
     * Method that upgrades the database
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE); 

        // Create tables again
        onCreate(db);


    }

    /**
     * All CRUD operations
     */
    // Adding new score details (Name, score, date)
    void addScore(Score score) {
        SQLiteDatabase db = this.getWritableDatabase();

        //ContentValues- holds the values.
        ContentValues values = new ContentValues();
        values.put(COL_NAME, score.getName()); // Contact Name
        values.put(COL_SCORE, score.getScore()); // Contact Phone

        // Inserting Row (i.e. the values that were entered from above
        db.insert(TABLE_SCORE, null, values);
        db.close(); // Closing database connection

}
    /**
     * Method will return a single Name and score
     * @param id
     * @return
     */
    // Getting single contact
    Score getScore(String name) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_SCORE, new String[] { COL_NAME,
                COL_SCORE}, COL_NAME + "=?",
                new String[] { String.valueOf(name) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Score score = new Score(cursor.getString(0),Integer.parseInt(cursor.getString(1)));
        // return contact
        return score;
    }

    /**
     * Method will return a list of all the scores
     * @return
     */
    // Getting All Contacts
    public List<Score> getAllScores() {
        List<Score> scoreList = new ArrayList<Score>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_SCORE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Score score = new Score();
                score.setName(cursor.getString(0));
                score.setScore(Integer.parseInt(cursor.getString(1)));
                // Adding contact to list
                scoreList.add(score);
            } while (cursor.moveToNext());
        }

        // return contact list
        return scoreList;
    }

}

以下代码是将数据写入数据库的代码部分。

即。添加了一个Score对象,其中包含Name和Score列。在这里,我还想在我添加到数据库的Date列中添加数据创建日期。我该怎么做?

/**


    * CRUD Operations
                 * */
                // Inserting Contacts
                Log.d("Insert: ", "Inserting ..");
                db.addScore(new Score(UserName.getUserName(), score));

                // Reading all contacts
                Log.d("Reading: ", "Reading all contacts..");
                List<Score> scores = db.getAllScores();

                for (Score s : scores) {
                    String log = "Name: " + s.getName() + " ,Score: " + s.getScore();
                    // Writing Contacts to log
                    Log.d("Name: ", log);
                }

更新:

现在收到以下错误:

07-02 21:31:44.785: E/SQLiteLog(2757): (1) table scores has no column named date
07-02 21:31:44.785: E/SQLiteDatabase(2757): Error inserting score=4 date=1404336704680 name=RooosYoungKen
07-02 21:31:44.785: E/SQLiteDatabase(2757):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)

尝试使用以下内容实现日期时:

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 2;

    // Database Name
    private static final String DATABASE_NAME = "MultapplyDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "scores";

    // Contacts Table Columns names
    private static final String COL_NAME = "name";
    private static final String COL_SCORE = "score";
    private static final String COL_DATE = "date";



    /**
     * Constructor
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        //NOTE: may need to alter the below to take out everything after INTEGER
        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "("
                + COL_NAME + " STRING PRIMARY KEY," + COL_SCORE + " INTEGER" + COL_DATE + "LONG" + ")";
        db.execSQL(CREATE_TABLE_SCORE);


    }

    /**
     * Method that upgrades the database
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE); 

        // Create tables again
        onCreate(db);


    }

    /**
     * All CRUD operations
     */
    // Adding new score details (Name, score, date)
    void addScore(Score score) {
        SQLiteDatabase db = this.getWritableDatabase();

        //ContentValues- holds the values.
        ContentValues values = new ContentValues();
        values.put(COL_NAME, score.getName()); 
        values.put(COL_SCORE, score.getScore()); 
        values.put(COL_DATE, score.getDate());


        // Inserting Row (i.e. the values that were entered from above
        db.insert(TABLE_SCORE, null, values);
        db.close(); // Closing database connection

}
    /**
     * Method will return a single Name and score
     * @param id
     * @return
     */
    // Getting single contact
    Score getScore(String name) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_SCORE, new String[] { COL_NAME,
                COL_SCORE, COL_DATE}, COL_NAME + "=?",
                new String[] { String.valueOf(name) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Score score = new Score(cursor.getString(0),Integer.parseInt(cursor.getString(1)),cursor.getLong(2));
        // return contact
        return score;
    }

    /**
     * Method will return a list of all the scores
     * @return
     */
    // Getting All Contacts
    public List<Score> getAllScores() {
        List<Score> scoreList = new ArrayList<Score>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_SCORE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Score score = new Score();
                score.setName(cursor.getString(0));
                score.setScore(Integer.parseInt(cursor.getString(1)));
                score.setDate(cursor.getLong(2));
                // Adding contact to list
                scoreList.add(score);
            } while (cursor.moveToNext());
        }

        // return contact list
        return scoreList;
    }

}

和其他班级一样:

/ **          * CRUD操作          * * /         //插入联系人         Log.d(&#34; Insert:&#34;,&#34; Inserting ..&#34;);         db.addScore(new Score(UserName.getUserName(),score,System.currentTimeMillis())); //需要在这里添加日期

    // Reading all contacts
    Log.d("Reading: ", "Reading all contacts..");
    List<Score> scores = db.getAllScores();

    for (Score s : scores) {
        String log = "Name: " + s.getName() + " ,Score: " + s.getScore() + "Date: " + s.getDate();
        // Writing Contacts to log
        Log.d("Name: ", log);
    }
}

1 个答案:

答案 0 :(得分:0)

请看这个链接:

http://www.sqlite.org/datatype3.html

不幸的是,SQLite没有DATE类型,但是我建议将当前时间转换为带有long的{​​{1}},将该值作为REAL或LONG插入到sqlite表中。如果要检索它,可以使用long dbLong = System.currentTimeMillis()