所以我搜索了一些关于这个主题的问题,但我已经意识到这些问题与你是否被允许创建没有PK等的表格有关。我的问题是以下代码生成错误:E/SQLiteLog: (1) near "FOREIGN": syntax error
代码:
CREATE TABLE tblPart(PartNumber [nvarchar](15) PRIMARY KEY NOT NULL,
PartDescription [nvarchar](150) NOT NULL);
CREATE TABLE tblStock(PartNumber [nvarchar](15) FOREIGN KEY REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH [int] NOT NULL);
在MSSQLSERVER
中执行此代码效果很好,但是当使用Java/Android
在SQLite
中运行时会产生错误。
提前感谢您的协助。
编辑:
DataHandler类:
public myDAL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//region create tblPart
sbCreatePart.append("CREATE TABLE " + TABLE_PART + "(");
sbCreatePart.append(COLUMN_PART_PARTNR + " [nvarchar](15) PRIMARY KEY NOT NULL, ");
sbCreatePart.append(COLUMN_PART_DESCRIPTION + " [nvarchar](150) NOT NULL)");
//endregion
//region create tblCurrentStock
sbCreateCurrStock.append("CREATE TABLE " + TABLE_CURRENTSTOCK + "(");
sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_PARTNR + " [nvarchar](15) FOREIGN KEY REFERENCES "
+ TABLE_PART + "(" + COLUMN_PART_PARTNR + ") ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, ");
sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_STOCKOH + " [int] NOT NULL)");
//endregion
db.execSQL(sbCreatePart.toString());
Log.d("Test", "tblPart");
db.execSQL(sbCreateCurrStock.toString());
Log.d("Test", "tblCurrStock");
}
public boolean TestInsert()
{
boolean result = true;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
try
{
values.put(COLUMN_PART_PARTNR, "PNTest123");
values.put(COLUMN_PART_DESCRIPTION, "Dummy Test Part");
Log.d("Test Input", "Values Added");
db.insert(TABLE_PART, null, values);
Log.d("Test Input", "Insert Successful");
}
catch (Exception ex)
{
result = false;
}
finally
{
db.close();
}
return result;
}
活动类:
public void onPartsClick(View v)
{
myDAL dal = new myDAL(this, null, null, 1);
boolean x = dal.TestInsert();
if(x)
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:4)
你有语法错误试试这个:
CREATE TABLE tblPart(PartNumber nvarchar(15) PRIMARY KEY NOT NULL,
PartDescription nvarchar(150) NOT NULL);
CREATE TABLE tblStock(PartNumber nvarchar(15) REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH integer NOT NULL);
如果将外键定义放在列定义上,则不需要FOREIGN KEY
。
或尝试这样:
CREATE TABLE tblStock10(PartNumber nvarchar(15),
StockOH integer NOT NULL,
FOREIGN KEY (PartNumber) REFERENCES tblPart1(PartNumber)
ON UPDATE SET NULL);