2

我的表中有外键约束,但是当我使用终端插入数据时它工作正常,但是当我在 xcode 项目中这样做时,它不工作可能是什么问题。如何通过程序启用 pragma foreign_keys = ON。我正在使用下面的代码进行插入,但我认为未启用外键。告诉我如何通过程序启用外键。

+(BOOL)insertEmployee:(int)din :(NSString*)name{

NSArray *arrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strDestPath = [NSString stringWithFormat:@"%@/samplepillbox1.sqlite",[arrDocPath objectAtIndex:0]];

sqlite3 *dbEmployee;
if(sqlite3_open([strDestPath UTF8String], &dbEmployee)==SQLITE_OK)
{

    //NSString *insertQuery = [NSString stringWithFormat:@"insert into maintable_master(din,brand_name) values(%d,'%@')",din,name];
    //NSString *insertQuery = [NSString stringWithFormat:@"insert into doctor_master(din,firstname) values(%d,'%@')",din,name];
    NSString *insertQuery = [NSString stringWithFormat:@"insert into schedule_master(din,start_date) values(%d,'%@')",din,name];
    void *v;
    char *errmsg;
    if(sqlite3_exec(dbEmployee, [insertQuery UTF8String], 0, v, &errmsg)==SQLITE_OK)
    {
        NSLog(@"inserted successfully");
        return YES;
    }
}
return NO;}
4

1 回答 1

4

您应该能够像运行更标准的 SQL 语句一样设置 pragma。通常,您在打开数据库连接后立即设置 pragma。

所以你的代码应该看起来像这样:

// 1. open the connection
...

// 2. set the pragma
if (sqlite3_exec(dbEmployee, @"PRAGMA foreign_keys = ON", 0, v, &errmsg) != SQLITE_OK)
{
    NSLog(@"failed to set the foreign_key pragma");
    return -1;
}
于 2012-04-28T09:44:10.680 回答