android中的SQLite数据库中有多个表?

时间:2011-04-14 20:18:25

标签: android sqlite

我在android中的sqlite数据库中创建多个表时遇到问题。 这是我的代码

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

1 个答案:

答案 0 :(得分:1)

增加DATABASE_VERSION的值,否则不会调用onUpgrade。

我注意到你没有删除onUpgade中的SETTING_TABLE,并且你在代码顶部丢失了第一个insert语句,因为你用INSERTSETTING替换了INSERT。