i have a simple sqllite databas开发者_运维技巧e with 2 columns and multiple rows. e.g.
Code1 1000
Code2 2000
Code3 3000
Code4 4000
Code5 5000
I want to add all the fields together e.g. code1,code2,code3,code4,code5 and return the total between them to a label in my interface builder. How could i do this using the iphone sdk?are there any tutorials out there? thanks for any help on this.
You'll find a great tutorial here which will cover both the UI and the database part: http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_4_iPhone_Application
In summary, it would be something like this:
In 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
In 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
Something like that... then you just call getTotal in viewDidLoad (or whenever you press a button).
精彩评论