数据库表未创建,未调用onCreate

时间:2014-02-16 14:11:00

标签: android

这是我的代码:

public class ProductOrderHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "ckredisDB";
private static final int DATABASE_VERSION = 10;
/* ALL COLUMNS */
public static final String TABLE_PRODUCT_ORDER = "order_products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_ORDER_ID = "orderId";
public static final String COLUMN_PRODUCT_ID = "productId";
/* ALL COLUMNS ARRAY */
private String[] allColumns = {
        COLUMN_ID,
        COLUMN_ORDER_ID,
        COLUMN_PRODUCT_ID
};

// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
        + TABLE_PRODUCT_ORDER + "(" + COLUMN_ID + " integer primary key autoincrement, "
        + COLUMN_ORDER_ID + " integer not null, "
        + COLUMN_PRODUCT_ID + " integer not null);";

private SQLiteDatabase database;

public ProductOrderHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
    database.execSQL("CREATE INDEX orderId_index ON " + TABLE_PRODUCT_ORDER + "(" + COLUMN_ORDER_ID + ")", null);
    database.execSQL("CREATE INDEX productId_index ON " + TABLE_PRODUCT_ORDER + "(" + COLUMN_PRODUCT_ID + ")", null);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCT_ORDER);
    onCreate(db);
}
/* REPOSITORY THING */

private void open() throws SQLException {
    database = this.getWritableDatabase();
}
public long createEntry(ProductOrderModel e) {
    ContentValues values = new ContentValues();

    values.put(COLUMN_ORDER_ID, e.getOrderId());
    values.put(COLUMN_PRODUCT_ID, e.getProductId());

    this.open();
    long insertId = database.insert(TABLE_PRODUCT_ORDER, null,values);
    this.close();

    return insertId;
}
}

然后我正在尝试添加新行:

prodOrdHelp = new ProductOrderHelper(this);
ProductOrderModel pm = new ProductOrderModel();
pm.setProductId(indexedProductIds.get(i));
pm.setOrderId(orderId);
prodOrdHelp.createEntry(pm);

例外:

插入orderId = 2 productId = 5231时出错     android.database.sqlite.SQLiteException:没有这样的表:order_products(代码1):,编译时:INSERT INTO order_products(orderId,productId)VALUES(?,?)

同样我注意到,onCreate的方法永远不会被调用(即使我更改了DATABASE_VERSION)...问题出在哪里?

1 个答案:

答案 0 :(得分:1)

这两行是完全错误的:

database.rawQuery("CREATE INDEX orderId_index ON '" + TABLE_PRODUCT_ORDER + "'('" + COLUMN_ORDER_ID + "')", null);
database.rawQuery("CREATE INDEX productId_index ON '" + TABLE_PRODUCT_ORDER + "'('" + COLUMN_PRODUCT_ID + "')", null);

1 - rawQuesry只执行QUERIES(这是“SELECT”语句而不是其他)不是命令。您应该使用exexSQL,如上面这两行中那样。

2 - 那些撇号(')是什么?尽快删除它们。