【问题标题】:how to retrieve data from SQLite using iphone sdk?如何使用 iphone sdk 从 SQLite 检索数据?
【发布时间】:2011-08-30 12:51:34
【问题描述】:

我有一个简单的 sqllite 数据库,它有 2 列和多行。例如

Code1 1000
Code2 2000
Code3 3000
Code4 4000
Code5 5000

我想将所有字段添加在一起,例如code1,code2,code3,code4,code5 并将它们之间的总数返回到我的界面构建器中的标签。我怎么能用 iphone sdk 做到这一点?那里有任何教程吗?感谢您对此的任何帮助。

【问题讨论】:

    标签: iphone objective-c database sqlite ios4


    【解决方案1】:

    您会在此处找到涵盖 UI 和数据库部分的精彩教程:http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_4_iPhone_Application

    总而言之,应该是这样的:

    在databaseViewController.h中,

    #import <UIKit/UIKit.h>
    #import "/usr/include/sqlite3.h"
    
    @interface databaseViewController : UIViewController {
            UILabel *total;
            NSString *databasePath;
            sqlite3 *db;
    }
    @property (retain, nonatomic) IBOutlet UILabel *total;
    - (IBAction) getTotal;
    @end
    

    在databaseViewController.m中,

    #import "databaseViewController.h"
    
    @implementation databaseViewController
    @synthesize total;
    
    -(void) getTotal
    {
        sqlite3_stmt    *statement;
    
        const char *dbpath = [databasePath UTF8String];
    
        if (sqlite3_open(dbpath, &db) == SQLITE_OK)
        {
                NSString *totalSQL = [NSString initWithUTF8String: @"SELECT SUM(field2) FROM MyTable"];
                const char *total_stmt = [totalSQL UTF8String];
    
                sqlite3_prepare_v2(db, total_stmt, -1, &statement, NULL);
                if (sqlite3_step(statement) == SQLITE_ROW)
                {
                 NSString *totalField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
                             total.text = totalField;
                }
                sqlite3_finalize(statement);
                sqlite3_close(contactDB);
        }
    }
    .
    .
    .
    - (void)viewDidUnload {
            self.total = nil;
    }
    
    - (void)dealloc {
        [total release];
            [super dealloc];
    }
    @end
    

    类似的东西...然后您只需在 viewDidLoad 中调用 getTotal (或每当您按下按钮时)。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2017-07-16
      • 2019-02-21
      • 1970-01-01
      • 2011-08-30
      • 2011-08-07
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      相关资源
      最近更新 更多