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

Android SQLite:在数据库中添加日期列,android,mysql,sql,database,sqlite,Android,Mysql,Sql,Database,Sqlite,在我当前的应用程序中,有一个SQLite数据库正在按预期运行。但是,我想在数据库中添加一列date 如何将此列添加到下面的DatabaseHelper类中 DatabaseHelper类: public class DatabaseHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name

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

如何将此列添加到下面的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;
    }

}
尝试使用以下方法实施日期时:

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;
    }
}

和其他类别:

/** *积垢作业 * */ //插入联系人 Log.dInsert:,插入。。; db.addScorenew ScoreUserName.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);
    }
}
请参阅此链接:


不幸的是,SQLite没有日期类型,但是我建议将当前时间转换为long,long dbLong=System.currentTimeMillis,将该值作为实数或long插入SQLite表中。当您想要检索它时,您可以使用Date timestamp=new DatedbLong

这里的设计似乎很愚蠢……是否为每个分数/名称组合创建一个新表?简短的回答是修改create_table_score,以便在构建语句时包含日期列。Long answer=为什么要这样添加和删除表?我不知道如何包含日期列,也不知道如何在程序中向其中添加数据?可以将时间戳作为长值存储在数据库中。好的,谢谢,但是如何在代码中创建它?不是在创建数据库的地方,也不是在输入数据的地方。谢谢,请查看我的代码更新。我试着使用你说的方法,但是我得到了另一个错误。我看到你更新了你的创建查询,但是如果我没有弄错的话,在你的onCreateSQLite数据库方法中应该有一个,after整数,实际上我让它工作了!谢谢!时间戳是system.currentTimeMillis的可读版本吗?时间戳是一个java.util.Date对象,可以根据需要以不同的方式格式化。您存储的LONG值基本上是自1970年1月1日00:00:00 GMTThanks以来的毫秒数!是否有任何方法可以将1970年以来的毫秒值转换为日期和时间,以便以该形式存储在SQLite数据库中?
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;
    }
    // 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);
    }
}