如何在现有数据库中添加表?

时间:2018-07-12 09:32:33

标签: android

这是我的数据库代码。如何向其中添加新表?

public class DatabaseHelper extends SQLiteOpenHelper {

    // Table Name
    public static final String TABLE_NAME = "COUNTRIES";


    // Table columns
    public static final String _ID = "_id";
    public static final String SUBJECT = "subject";
    public static final String DESC = "description";
    public static final String DESC2 = "description2";
    public static final String DESC3 = "description3";

    // Database Information
    static final String DB_NAME = "Ar.DB";

    // database version
    static final int DB_VERSION = 3;

    // Creating table query
    private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, " + DESC + " TEXT, " + DESC2 + " TEXT, " + DESC3 + " TEXT);";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

如果有人知道,只需添加用于插入新表的代码,这样对我来说也很容易。

2 个答案:

答案 0 :(得分:0)

onUpgrade()方法中,您可以在现有数据库中添加新表,如下所示:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  if (newVersion == 4) {
     // Create New Table
  }
}

注意:您必须将DB_VERSION = 4更改为onUpgrade呼叫

答案 1 :(得分:0)

为要插入数据库中的第二个表创建另一个字符串查询。

这样的事情。

public class DBHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "my_db";

private static final int DATABASE_VERSION = 1;

// Database creation sql statement
public static final String Table1 = "create table table1name ("Your columns");";


public static final String Table2 = "create table table2name ("Your columns");";


public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(Table1);
   database.execSQL(Table2);

}

// Method is called during an upgrade of the database, e.g. if you increase
// the database version
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
        int newVersion) {

    database.execSQL("DROP TABLE IF EXISTS " + Table1);
    database.execSQL("DROP TABLE IF EXISTS " + Table2);

    onCreate(database);
}


public boolean deleteDatabase(Context context) {
        return context.deleteDatabase(DATABASE_NAME);
}

}

现在为每个表创建CRUD方法。