简体   繁体   English

Android中SQLite数据库中的多个表?

[英]More than one table in SQLite database in android?

I am facing problem in creating more than one tables in sqllite database in android. 我在android的sqllite数据库中创建多个表时遇到问题。 Here is my code 这是我的代码

   public class DataHelper {
   private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";
   private static final String SETTING_TABLE="setting";

   private Context context;
   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;
   private static final String INSERT = "insert into " + TABLE_NAME + 
       "(name) values (?)";
   private static final String INSERTSETTING = "insert into " + SETTING_TABLE +
       "(name) values (?)";

   public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
      this.insertStmt = this.db.compileStatement(INSERTSETTING);
   }

   public SQLiteDatabase getDb() {
      return this.db;
   }

   public long insert(String name) {
      this.insertStmt.bindString(1, name);
      return this.insertStmt.executeInsert();
   }   
   private static class OpenHelper extends SQLiteOpenHelper {
      OpenHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + TABLE_NAME + 
              " (id INTEGER PRIMARY KEY, name TEXT)");
         db.execSQL("CREATE TABLE " + SETTING_TABLE + 
              " (id INTEGER PRIMARY KEY, name TEXT)");
      }
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
      {
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
         onCreate(db);
      }
   }
}

Increase the value of DATABASE_VERSION, otherwise onUpgrade won't get called. 增加DATABASE_VERSION的值,否则onUpgrade不会被调用。

I notice you don't drop the SETTING_TABLE in onUpgade, and you're losing the first insert statement at the top of your code, as you replace INSERT with INSERTSETTING. 我注意到您没有将SETTING_TABLE放在onUpgade中,并且在用INSERTSETTING替换INSERT时,您丢失了代码顶部的第一个插入语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM