- (void)viewDidLoad
{
[super viewDidLoad];// Do any additional setup after loading the view.
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Notebook1.sqlite"]];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSLog(@"%@",databasePath);
if ([fileMgr fileExistsAtPath:databasePath]==NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(@"hohoho, %s",dbpath);
if (sqlite3_open(dbpath, ¬eDB)==SQLITE_OK)
{
char *errMsg;
const char *sql_str = "CREATE TABLE IF NOT EXISTS Notebook1 (ID INTEGER PRIMARY KEY AUTOINCREMENT, Whattime Text, Address TEXT, What TEXT, Who TEXT, NOTE TEXT)";
if (sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg)!=SQLITE_OK)
{
NSLog(@"Failed to create table");
}
sqlite3_close(noteDB);
}
else
{
NSLog(@"Failed to open/create database");
}
}
self.title = @"Add new";
}
-(IBAction)addNote:(id)sender
{
char *errMsg;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, ¬eDB)==SQLITE_OK)
{
NSLog(@"we are here");
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO Notebook1(Whattime, Address, What, Who, Note) VALUES(\"%@\",\"%@\",\"%@\"\"%@\",\"%@\")", self.whenField.text, self.whenField.text, self.whenField.text,self.whenField.text, self.whenField.text];
const char *insert_stmt = [insertSQL UTF8String];
if (sqlite3_exec(noteDB, insert_stmt, NULL, NULL, &errMsg)==SQLITE_OK)
{
self.whenField.text = @"";
self.whereField.text = @"";
self.whatField.text = @"";
self.whoField.text = @"";
self.noteView.text = @"";
[self doAlert:@"add ok"];
}
else
{
NSLog(@"error: %s",errMsg);
sqlite3_free(errMsg);
}
sqlite3_close(noteDB);
}
}
在“viewDidLoad”中,程序创建了一个具有 6 个属性的 sqlite 表:ID、Whattime、Address、What、who、Note。在“addNote”中,我试图将一些数据插入到数据库中。但它没有这样做,日志显示:2013-10-12 05:10:49.328 Notebook[4266:a0b] error:4 values for 5 columns