java - Android SQLite DB 适配器更新 DB

标签 java android database sqlite

我发现一个数据库适配器在互联网上搜索 Android 资源。我目前正在尝试在数据库中存储位置等信息。我让它工作了,但是当我返回尝试添加更多列时,我收到诸如“该列不存在”之类的错误。所以我的问题是,如何删除数据库并使用这些新列重新创建它?这是我的代码,一切正常,直到我添加“stamp”字符串...

// ------------------------------------ DBADapter.java ---------------------------------------------

// TODO: Change the package to match your project.
package biz.tanners.geo_x;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {

    /////////////////////////////////////////////////////////////////////
    //  Constants & Data
    /////////////////////////////////////////////////////////////////////
    // For logging:
    private static final String TAG = "DBAdapter2";

    // DB Fields
    public static final String KEY_ROWID = "_id";
    public static final int COL_ROWID = 0;
    /*
     * CHANGE 1:
     */
    // TODO: Setup your fields here:
    public static final String KEY_NAME = "name";
    public static final String KEY_LONGITUDE = "longitude";
    public static final String KEY_LATTITUDE = "lattitude";
    public static final String KEY_STAMP = "stamp";

    // TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
    public static final int COL_NAME = 1;
    public static final int COL_LONGITUDE= 2;
    public static final int COL_LATTITUDE = 3;
    public static final int COL_STAMP = 4;


    public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_LONGITUDE, KEY_LATTITUDE, KEY_STAMP};
    public static final String DATABASE_NAME = "MyDb";
    public static final String DATABASE_TABLE = "mainTable";
    public static final int DATABASE_VERSION = 4;

    private static final String DATABASE_CREATE_SQL = 
            "create table " + DATABASE_TABLE 
            + " (" + KEY_ROWID + " integer primary key autoincrement, "

            /*
             * CHANGE 2:
             */
            // TODO: Place your fields here!
            // + KEY_{...} + " {type} not null"
            //  - Key is the column name you created above.
            //  - {type} is one of: text, integer, real, blob
            //      (http://www.sqlite.org/datatype3.html)
            //  - "not null" means it is a required field (must be given a value).
            // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
            + KEY_NAME + " text not null, "
            + KEY_LONGITUDE + " double not null, "
            + KEY_LATTITUDE + " double not null, " + KEY_STAMP + " text not null"

            // Rest  of creation:
            + ");";

    // Context of application who uses us.
    private final Context context;

    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    /////////////////////////////////////////////////////////////////////
    //  Public methods:
    /////////////////////////////////////////////////////////////////////

    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to the database.
    public long insertRow(String name, double longitude, double lattitude, String stamp) {
        /*
         * CHANGE 3:
         */     
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_LONGITUDE, longitude);
        initialValues.put(KEY_LATTITUDE, lattitude);
        initialValues.put(KEY_STAMP, stamp);

        // Insert it into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));              
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                            where, null, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String name, double longitude, double lattitude, String stamp) {
        String where = KEY_ROWID + "=" + rowId;

        /*
         * CHANGE 4:
         */
        // TODO: Update data in the row with new fields.
        // TODO: Also change the function's arguments to be what you need!
        // Create row's data:
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_NAME, name);
        newValues.put(KEY_LONGITUDE, longitude);
        newValues.put(KEY_LATTITUDE, lattitude);
        newValues.put(KEY_STAMP, stamp);

        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);           
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}

                                                           Error Code : 1 (SQLITE_ERROR)
                                                           Caused By : SQL(query) error or missing database.
                                                            (no such column: stamp (code 1): , while compiling: SELECT DISTINCT _id, name, longitude, lattitude, stamp FROM mainTable2)

最佳答案

我按照我的理解给你答案。您可以进行删除表查询,并在需要删除该表时调用该查询,并且每当您想要创建该表时,都可以进行创建表查询。

关于java - Android SQLite DB 适配器更新 DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38471591/

相关文章:

java - MyClass 无法转换为 java.lang.Comparable : java. lang.ClassCastException

android - 无论我尝试什么,AlertDialog 都不会包装内容

php - 检查IP地址是否存储在数据库中

database - 来自 bash 的简单数据库解决方案(本地存储)

mysql - sql - 从数据库中的所有对象名称中删除字符

java - 这有什么问题吗?找不到标志。符号 - 构造函数

java - 如何在 GET 方法中为 spring boot Controller 类传递多个路径变量?

java - 在 Android 中加载屏幕时出错

android - 应该有字幕 Controller 已经设置 Mediaplayer 错误 Android

javascript - 如何获取用户在手机上使用的浏览器版本?