在Database android中添加另一个表

时间:2015-12-10 16:20:55

标签: android sqlite

我可以用这种方式在我的数据库中添加另一个表吗?看到我的onupgrade我试过这种方式是可能的。每当我们添加或删除信息时,有一件事是数据库升级。??

public class DataBaseOperations extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "+
        mDatabase.Tableinfo.Table_Name +"("
        +mDatabase.Tableinfo.Name+" TEXT,"
        +mDatabase.Tableinfo.phone+" INTEGER,"
        +mDatabase.Tableinfo.status+" TEXT,"
        +mDatabase.Tableinfo.Pic+" BLOB"+")";
private static final String Contacts_Table = "CREATE TABLE "+
        mDatabase.Tableinfo.contacts +"("
        +mDatabase.Tableinfo.Contacts_id+" INTEGER PRIMARY KEY,"
        +mDatabase.Tableinfo.Contacts_name+" TEXT,"
        +mDatabase.Tableinfo.Contacts_phone+" INTEGER,"
        +mDatabase.Tableinfo.status_contact+" TEXT,"
        +mDatabase.Tableinfo.Contact_pic+" BLOB"+")";

public DataBaseOperations(Context context) {
    super(context, mDatabase.Tableinfo.Database_Name, null, DATABASE_VERSION);
}

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


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if(newVersion==1){
    db.execSQL(Contacts_Table);
    onCreate(db);

  }
}

这是我的合同类。

public class mDatabase {
public mDatabase(){
}
 public static abstract class Tableinfo{
 public static final String Name = "Name";
 public static final String status = "status";
 public static final String phone = "Phone";
 public static final String Pic  = "Pro_pic";
 public static final String Database_Name = "User_info.db";
 public static final String Table_Name = "User";
 public static final String contacts = "Contacts";
 public static final String Contacts_id= "Contact_id";
 public static final String Contacts_name = "Contacts name";
 public static final String Contacts_phone = "Contacts phone No";
 public static final String status_contact = "Status";
 public static final String Contact_pic = "pic";
}
}

1 个答案:

答案 0 :(得分:0)

没有

您的onUpgrade只需致电

db.execSQL(SQL_CREATE_ENTRIES);

然后重定向到

onCreate(db);

再次调用相同的东西。

看看这个答案。它提供了一种更好的方法来处理升级。

Upgrade database on deployed Android app on update

作为澄清。仅当数据库不存在时才会调用onCreate

如果数据库存在,则调用

onUpgrade并且现有数据库版本号低于您在OpenHelper的构造函数中使用的版本号。

如果数据库xists和版本号相同,则调用NEITHER。