当我在iOS上尝试使用SQLite时,INSERT和UPDATE无法正常工作 [英] When I try SQLite on iOS, INSERT and UPDATE does not work
问题描述
我在user.db
中创建了一个表,该文件位于我的xcode项目文件夹中.
I createed a table in user.db
, this file is in my xcode project folder.
create table user (uid INTEGER PRIMARY KEY ASC AUTOINCREMENT, username, mobile);
接下来,在应用程序委托.m
文件中,插入两行,然后查询select * from user
并将其打印.
Next, in the app delegate .m
file, I insert two rows, then I query select * from user
and print it.
但是,使用语句和sqlite3_exec,插入不会成功,并且完全没有错误. user.db
具有我从sqlite命令行插入的3行.当我运行该应用程序时,它会打印5行数据,我会插入2行,但是当我在sqlite命令行中查询时,仍然有3行,是否没有提交两个新行?
However, use statement and sqlite3_exec, the insertions are not successful, and there are no errors at all. user.db
has 3 rows I inserted from sqlite command line. When I run this app, it prints 5 rows of data, 2 rows are inserted by me, but when I query in sqlite command line, there are still 3 rows, the two newer rows are not committed?
我还运行sqlite3_get_autocommit
,并找到了autocommit=1
,那么我错过了什么导致这种情况发生?
I also run sqlite3_get_autocommit
, and find out autocommit=1
, so what have I missed to cause this to happen?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
NSString* file = [[NSBundle mainBundle] pathForResource:@"user" ofType:@"db"];
sqlite3* database = NULL;
if(sqlite3_open([file UTF8String], &database) == SQLITE_OK)
{
NSLog(@"database open successfully.");
// stmt
// int autocommit = sqlite3_get_autocommit(database);
sqlite3_stmt* stmt;
static char * sql = "insert into user (username, mobile) values('xxxx', '5555555');commit;";
int success = sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);
if(success != SQLITE_OK)
{
NSLog(@"create stmt failed");
}
success = sqlite3_step(stmt);
if(success != SQLITE_OK)
{
NSLog(@"insert failed");
}
sqlite3_finalize(stmt);
sqlite3_exec(database, "begin;insert into user (username, mobile) values('yyyy', '666666');commit;", NULL, NULL, 0);
// insert
char *zErrMsg = 0;
int rc = sqlite3_exec(database, "select * from user", MyCallback, 0, &zErrMsg);
if(rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
}
}
sqlite3_close(database);
return YES;
}
推荐答案
您无法更新存储在应用程序资源中的数据库.尝试将数据库复制到应用程序的Document或Library文件夹中,然后在那里更新数据库.
You can't update databases stored in the app resources. Try copying the database to your app's Document or Library folder and then updating the database there.
这篇关于当我在iOS上尝试使用SQLite时,INSERT和UPDATE无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!