zoukankan      html  css  js  c++  java
  • 使用SQLite数据库存储数据(2)向表中插入记录

    向表中插入记录

    向数据表Notebook中添加一条新的记事日志,成功插入记录后,会显示一个提醒视图。
    - (IBAction)addNote:(id)sender {
    char *errMsg;

    const char *dbpath = [databasePath UTF8String];

    if(sqlite3_open(dbpath, &noteDB) == SQLITE_OK){
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO Notebook(Whattime, Address, What, Who, Note) VALUES(\"%@\", \"%@\",\"%@\", \"%@\", \"%@\")", self.whenField.text, self.whereField.text, self.whatField.text, self.whoField.text, self.noteView.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:@"添加成功!"];
    } else {
    NSLog(@"插入记录错误: %s", errMsg);
    sqlite3_free(errorMsg);
    }

    sqlite3_close(noteDB);
    }
    }
    显示提醒视图的代码:
    - (void)doAlert:(NSString *)inMessage{
    UIAlertView *alertDialog;
    alertDialog = [[UIAlertView alloc]
    initWithTitle:@"提示消息" message:inMessage  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertDialog show];
    }

    错误信息的处理

    如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串- sqlite3_free(errorMsg),示例代码如下所示:
    if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {
    NSLog(@"create ok.");
    }else {
    NSLog(@"error: %s",errorMsg);
    sqlite3_free(errorMsg);
    }

    范例App运行界面如下图所示。本教程的具体内容及其范例App都收录在《一步一步学习iOS 6 编程》的最新版PDF文件中。

  • 相关阅读:
    POJ 1269 Intersecting Lines --计算几何
    URAL 2014 Zhenya moves from parents --线段树
    HDU 4122 Alice's mooncake shop --RMQ
    HDU 4121 Xiangqi --模拟
    HDU 4045 Machine scheduling --第二类Strling数
    HDU 4041 Eliminate Witches! --模拟
    HDU 5105 Math Problem --数学,求导
    2014-2015 Codeforces Trainings Season 2 Episode 7 G Gophers --线段树
    HDU 4419 Colourful Rectangle --离散化+线段树扫描线
    HDU 5102 The K-th Distance
  • 原文地址:https://www.cnblogs.com/tuncaysanli/p/2727951.html
Copyright © 2011-2022 走看看