sqlite表创建

时间:2012-05-05 19:01:12

标签: java android sqlite

我不确定我的问题。当查询第二个表时,我没有得到这样的表..这些都在onCreate方法

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_CBID
                   + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
                   + " TEXT NOT NULL, " + KEY_RACE + " TEXT NOT NULL,"
                   + KEY_CLASS + " TEXT NOT NULL," + KEY_DEITY
                   + " TEXT NOT NULL," + KEY_GENDER + " TEXT NOT NULL,"
                   + KEY_HEIGHT + " TEXT NOT NULL," + KEY_WEIGHT
                   + " TEXT NOT NULL);");

        db.execSQL("CREATE TABLE " + DATABASE_TABLE2 + " (" + KEY_CSID
                   + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SKILL
                   + " TEXT NOT NULL, " + KEY_CBID + " INTEGER PRIMARY KEY FOREIGN KEY);"
                   );

编辑:显示cvs

String skill = "blah test";
    Cursor c = ourDatabase.rawQuery("SELECT " + KEY_CBID + " FROM " + DATABASE_TABLE + " order by " + KEY_CBID + " DESC limit 1", null);
    if (c != null)
    {
        c.moveToFirst();
        cbid = c.getInt(0);
    }

    ContentValues cv = new ContentValues();
    cv.put(KEY_SKILL, skill);
    cv.put(KEY_CBID, cbid);
    return ourDatabase.insert(DATABASE_TABLE2, null, cv);

我的选择陈述是:

Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SKILL + ", " + KEY_NAME + ", " + KEY_CBID + " FROM " + DATABASE_TABLE + ", " + DATABASE_TABLE2 + " WHERE " + DATABASE_TABLE +"."+KEY_CBID+" = " +DATABASE_TABLE2+"."+KEY_CBID+" && " +DATABASE_TABLE+"."+KEY_NAME+" = '"+item+"'", null); 

2 个答案:

答案 0 :(得分:2)

我不相信您的第二个表正在创建,以下是如何使用外键声明表:

CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);

CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);

我从SQLite.org获取了这些内容。

在SQLite中默认禁用外键,Android用途:

db.execSQL("PRAGMA FOREIGN_KEYS=ON;");

在插入数据之前,如果你还没有;

答案 1 :(得分:0)

  1. 检查您是否记录cat以查看创建第二个表时是否有错误。 如果sqllite出现错误,则会记录在logcat

  2. 将新表添加到DB时,请确保已升级DB 如果您正在调用db.open,则从您的代码中获取IF,如果数据库已经创建,则它将被打开。因此,在这种情况下,不会命中创建新表的代码。因此,您必须确保升级数据库,以便删除所有现有表并重新创建

    @覆盖     public void onCreate(SQLiteDatabase db){

        createAllTables(db);
        Log.v(DBTAG, "DATABASE CREATED");
        // Toast.makeText(mCtx, "created", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DBTAG, "Upgrading database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data");
        dropExistingTables(db);
        onCreate(db);
    }
    
    private void dropExistingTables(SQLiteDatabase db) {
    
        for (int i = 0; i < Utils.getDropTableQueries().size(); i++) {
            db.execSQL(Utils.getDropTableQueries().get(i));
        }
    }
    
  3. 因此得出结论确保您正在创建表,并且在创建时没有错误。