ios 怎么打开sqlite数据库
发布网友
发布时间:2022-04-28 18:34
我来回答
共1个回答
热心网友
时间:2022-04-08 05:34
ITJOB题库中也有这道题,大概过程是这样。新建Empty Appliation,添加一个HomeViewController,和一个组件libsqlite3.dylib,来支持对sqlite3的连接,关闭,增删改查等操作。
1. HomeViewController.h代码:
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface HomeViewController : UIViewController{
sqlite3 *db; //声明一个sqlite3数据库
}
- (NSString *)filePath;//数据库文件的路径。一般在沙箱的Documents里边操作
@end
2. HomeViewController.m代码:
#import "HomeViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
//该方法用于返回数据库在Documents文件夹中的全路径信息
- (NSString *)filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"Contacts.sqlite"];
}
//打开数据库的方法
- (void)openDB{
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, @"数据库打开失败。");
}
}
- (void)getAllContacts{
NSString *sql = @"SELECT * FROM members";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *name = (char *)sqlite3_column_text(statement, 0);
NSString *nameStr = [[NSString alloc] initWithUTF8String:name];
char *email = (char *)sqlite3_column_text(statement, 1);
NSString *emailStr = [[NSString alloc] initWithUTF8String:email];
char *birthday = (char *)sqlite3_column_text(statement, 2);
NSString *birthdayStr = [[NSString alloc] initWithUTF8String:birthday];
NSString *info = [[NSString alloc] initWithFormat:@"%@ - %@ - %@",
nameStr, emailStr, birthdayStr];
NSLog(info);
[nameStr release];
[emailStr release];
[birthdayStr release];
[info release];
}
sqlite3_finalize(statement);
}
}