【问题标题】:Error writing to SQLite DB写入 SQLite DB 时出错
【发布时间】:2011-05-10 21:01:34
【问题描述】:

这是我第一次使用 SQL,我认为我做的一切都是正确的,但我不断收到我的表不存在的错误。要创建我所做的表:

CREATE TABLE "Users" ("UserID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "UserName" VARCHAR, "Password" VARCHAR)

所以我有一个名为 Users 的表

要写入我正在调用的表:

- (void) addUser {

if(addStmt == nil) {
    const char *sql = "insert into Users(UserName, Password) values (?, ?)";
    if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
        NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}

sqlite3_bind_text(addStmt, 1, [userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [password UTF8String], -1, SQLITE_TRANSIENT);

if(SQLITE_DONE != sqlite3_step(addStmt))
    NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
    //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
    userID = sqlite3_last_insert_rowid(database);

//Reset the add statement.
sqlite3_reset(addStmt);
}

当我触发它时,它会关闭应用程序并给我错误 Error while creating add statement. 'no such table: Users'

我花了好几天才走到这一步,我不知道从这里到哪里去。我该怎么做才能解决这个问题?

编辑: 这就是我在 AppDelegate 文件中导入数据库的方式

- (NSString *) getDBPath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"UserDatabase.sqlite"];
}

【问题讨论】:

    标签: iphone sql objective-c ios sqlite


    【解决方案1】:

    我很确定您会收到此错误,因为 sqlite 找不到您的 sqlite 文件,因此它会创建一个空数据库。而且在空数据库中,它显然找不到您的表,因此会出现错误。

    因此,正确访问数据库文件应该是您的重点。从您的代码看来,您是从文档目录中读取它的 - 但如果您不将它复制到该目录,您的 db 文件将无法到达那里。

    尝试将实际的 sqlite 文件添加到您的包中。然后,使用此代码到达您的 sqlite 文件的路径:

    databasePath = [[NSBundle mainBundle] pathForResource:@"UserDatabase" ofType:@"sqlite"];
    

    我相信这会解决您的问题。但是,您应该注意,如果您想保存对该数据库的更改,并且我认为您想要,您不会将文件复制到文档目录,因为捆绑文件是只读的。在这种情况下,您将在目录路径中搜索 sqlite 文件,如果没有找到(可能是第一次使用 app) - 将其从包中复制到该目录。

    【讨论】:

    • 这样的声音会起作用。打开其他文件时,我多次遇到此问题。如果我将 SQL 文件放在服务器上,我会这样做吗?还是我必须让 FTP 参与进来?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2017-03-22
    • 2017-01-28
    • 1970-01-01
    相关资源
    最近更新 更多