【发布时间】:2016-12-06 21:17:14
【问题描述】:
我正在尝试在 iPhone 应用程序中将值插入我的 sqlite 数据库。在数据库 insertSQL 上插入值显示 nil 值。值未添加到数据库。值未插入创建数据库。第一个函数创建数据库连接,student.db是数据库名称。第二个函数可以输入值并在类上调用函数来保存数据,但insertSQL为nil。所以值不存储在数据库中。但没有成功: 在此先感谢..
代码..
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: @"student.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt ="create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(@"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(@"Failed to open/create database");
}
}
return isSuccess;
}
- (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
department:(NSString*)department year:(NSString*)year;
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:@"insert into studentsDetail (regno,name, department, year) values(\"%ld\",\"%@\", \"%@\", \"%@\")",(long)[registerNumber integerValue],name, department, year];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
-(IBAction)Save:(id)sender {
BOOL success = NO;
NSString *alertString = @"Data Insertion failed";
if (_regNo.text .length>0 &&_name.text.length>0 && _department.text.length>0 &&_year.text.length>0){
success = [[Sqlite getSharedInstance]saveData:
_regNo.text name:_name.text department:
_department.text year:_year.text];
}
else{
alertString = @"Enter all fields";
}
if (success == NO) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:
alertString message:nil
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
_regNo.text = @"";
_department.text = @"";
_name.text = @"";
_year.text = @"";
}
【问题讨论】:
-
使用 student.sqlite 代替 student.db。
标签: ios objective-c sqlite