无法在sqlite中创建带外键的表

时间:2015-06-21 06:14:03

标签: android sqlite foreign-keys

我的应用程序无法运行如果运行保持代码行db.execSQL(createOrderTable);db.execSQL(createOrderDetail);,这将创建两个带外键的表,摆脱它们应用程序运行正常。

这就是我对onCreate()方法的看法:

String createUserTable = "create table " + USER_TABLE +
            "(userID INTEGER PRIMARY KEY AUTOINCREMENT," +
            "userName TEXT NOT NULL," +
            "phoneNumber INTEGER);";
    String createProductTable = "create table " + PRODUCT_TABLE +
            "(productID INTEGER PRIMARY KEY AUTOINCREMENT," +
            "department TEXT,"+
            "name TEXT," +
            "price REAL," +
            "status NUMERIC);";
    String createOrderTable = "create table " + ORDER_TABLE +
            "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," +
            "FOREIGN KEY(userID) REFERENCES User(userID)," +
            "FOREIGN KEY(productID) REFERENCES Product(productID));";
    String createOrderDetail = "create table " + ORDER_DETAIL_TABLE +
            "(FOREIGN KEY(orderID) REFERENCES Order(orderID)," +
            "customerName TEXT," +
            "address TEXT," +
            "totalPrice REAL," +
            "quantity INTEGER);";
    db.execSQL(createUserTable);
    db.execSQL(createProductTable);
    db.execSQL(createOrderTable);
    db.execSQL(createOrderDetail);

这就是我对onUpgrade()所拥有的:

    db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + PRODUCT_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + ORDER_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + ORDER_DETAIL_TABLE);
    onCreate(db);

我现在如何创建其他两个表?有人可以帮忙吗?欣赏!

2 个答案:

答案 0 :(得分:0)

您没有在createOrderTable查询中创建列userId和productId,但尝试创建外键引用。首先创建一个列,然后引用它。

例如:

String createOrderTable = "create table " + ORDER_TABLE +
        "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," +
        "userID INTEGER,"+
        "productID INTEGER,"+
        "FOREIGN KEY(userID) REFERENCES User(userID)," +
        "FOREIGN KEY(productID) REFERENCES Product(productID));";
String createOrderDetail = "create table " + ORDER_DETAIL_TABLE +
        "(orderID INTEGER,"+
        "customerName TEXT," +
        "address TEXT," +
        "totalPrice REAL," +
        "quantity INTEGER," +
        "FOREIGN KEY(orderID) REFERENCES Order(orderID));";

答案 1 :(得分:0)

您必须先定义您的userID和productID列,然后在其上设置外键。

String createOrderTable = "create table " + ORDER_TABLE +
        "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," +
        " userID integer," +
        "FOREIGN KEY(userID) REFERENCES User(userID)," +
        "productID integer" 
        "FOREIGN KEY(productID) REFERENCES Product(productID));";