2011-04-14 63 views
1

我正面臨在android中的sqllite數據庫中創建多個表的問題。 這裏是我的代碼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); 
     } 
    } 
} 
+0

你有什麼問題? It1s可以在SQLite上創建多個表。 – 2011-04-14 20:22:01

+0

顯示您收到的錯誤.... – KevinDTimm 2011-04-14 20:22:47

+0

當我想添加第二個表時,它在一個表內工作正常,而不是它給了我錯誤(表不存在)。 – Altaf 2011-04-14 20:25:11

回答

1

增加DATABASE_VERSION的值,否則onUpgrade將不會被調用。

我注意到你不會在onUpgade中刪除SETTING_TABLE,並且在代碼頂部丟失第一個插入語句,因爲你用INSERTSETTING替換了INSERT。