SQLite只创建2个表

时间:2014-10-20 20:34:10

标签: java android sql sqlite

由于某些原因,SQLite只创建了两个表而不是4.我使用此代码:

@Override
public void onCreate(SQLiteDatabase db) 
{
    String TABLE_RECEIPT            = "CREATE TABLE RECEIPT (receiptId INTEGER PRIMARY KEY AUTOINCREMENT, receiptDate INTEGER); ";
    db.execSQL(TABLE_RECEIPT);

    String TABLE_PRODUCT            = "CREATE TABLE PRODUCT (productId INTEGER PRIMARY KEY AUTOINCREMENT, productName TEXT NOT NULL, productImagePath TEXT, productPrice REAL NOT NULL);";
    db.execSQL(TABLE_PRODUCT);

    String TABLE_RECEIPT_RULE       = "CREATE TABLE RECEIPT_RULE (receiptId INTEGER NOT NULL, productId INTEGER NOT NULL, ruleAmount INTEGER NOT NULL, PRIMARY KEY (receiptId, productId), FOREIGN KEY(receiptId) REFERENCES RECEIPT(receiptId), FOREIGN KEY(productId) REFERENCES PRODUCT(productId));";
    db.execSQL(TABLE_RECEIPT_RULE);

    String TABLE_PRODUCT_ATTRIBUTES = "CREATE TABLE PRODUCT_ATTRIBUTES (productId INTEGER NOT NULL, attributeName TEXT NOT NULL, attributeValue TEXT NOT NULL, PRIMARY KEY (productId, attributeName), FOREIGN KEY(productId) REFERENCES PRODUCT(productId));";
    db.execSQL(TABLE_PRODUCT_ATTRIBUTES);

    Log.i(Config.TAG, "Recreated database");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
    String TABLE_PRODUCT            = "DROP TABLE PRODUCT;";
    String TABLE_RECEIPT            = "DROP TABLE RECEIPT;";
    String TABLE_RECEIPT_RULE       = "DROP TABLE RECEIPT_RULE;";
    String TABLE_PRODUCT_ATTRIBUTES = "DROP TABLE PRODUCT_ATTRIBUTES;";

    db.execSQL(TABLE_PRODUCT);
    db.execSQL(TABLE_RECEIPT);
    db.execSQL(TABLE_RECEIPT_RULE);
    db.execSQL(TABLE_PRODUCT_ATTRIBUTES);
    onCreate(db);
}

消息Recreated database是可见的,因此它会尝试创建所有表。它没有显示任何类型的错误。

我不知道它是否有用,但我正在使用以下代码阅读现有表格:

//Placed in SQLiteStorage
public Cursor showAllTables(){
    String mySql = " SELECT name FROM sqlite_master " + " WHERE type='table'             "
            + "   AND name LIKE 'PR_%' ";
    return db.rawQuery(mySql, null);
}   

//In Activity, create the storage and calls the function 
Cursor c = new SQLiteStorage(this).showAllTables();
if (c.moveToFirst()) 
{
    while(!c.isAfterLast())
    {
        Log.i(Config.TAG, c.getString(0));
        c.moveToNext();
    }
}

1 个答案:

答案 0 :(得分:4)

在showAllTable函数中,您选择所有以PR开头的表,以便只在查询中显示产品表和产品属性表。

更改

String mySql =“SELECT name FROM sqlite_master”+“WHERE type ='table'”             +“并且命名为'PR_%'”;

String mySql =“SELECT name FROM sqlite_master”+“WHERE type ='table'”;