iphone连接mysql_iPhone 中数据库的使用方法

news/2025/2/4 9:58:01/

iPhone 中使用名为 SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、PHP、Java 等,还有 ODBC 接口,同样比起 Mysql、PostgreSQL 这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。

其使用步骤大致分为以下几步:

1. 创建DB文件和表格   2. 添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)   3. 通过 FMDB 的方法使用 SQLite

创建DB文件和表格

$ sqlite3 sample.dbsqlite> CREATE TABLE TEST(   ...>  id INTEGER PRIMARY KEY,   ...>  name VARCHAR(255)   ...> );

简单地使用上面的语句生成数据库文件后,用一个图形化SQLite管理工具,比如 Lita 来管理还是很方便的。

然后将文件(sample.db)添加到工程中。

添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)

首先添加 Apple 提供的 sqlite 操作用程序库 ibsqlite3.0.dylib 到工程中。位置如下

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS${VER}.sdk/usr/lib/libsqlite3.0.dylib

这样一来就可以访问数据库了,但是为了更加方便的操作数据库,这里使用 FMDB for iPhone。

svn co http://flycode.googlecode.com/svn/trunk/fmdb fmdb

如上下载该库,并将以下文件添加到工程文件中:

FMDatabase.hFMDatabase.mFMDatabaseAdditions.hFMDatabaseAdditions.mFMResultSet.hFMResultSet.m

通过 FMDB 的方法使用 SQLite

使用 SQL 操作数据库的代码在程序库的 fmdb.m 文件中大部分都列出了、只是连接数据库文件的时候需要注意 — 执行的时候,参照的数据库路径位于 Document 目录下,之前把刚才的 sample.db 文件拷贝过去就好了。

位置如下/Users/xxxx/Library/Application Support/iPhone Simulator/User/Applications/xxxx/Documents/sample.db

以下为链接数据库时的代码:

BOOL success;NSError *error;NSFileManager *fm = [NSFileManager defaultManager];NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];success = [fm fileExistsAtPath:writableDBPath];if(!success){  NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];  success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];  if(!success){    NSLog([error localizedDescription]);  }}// 连接DBFMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];if ([db open]) {  [db setShouldCacheStatements:YES];  // INSERT  [db beginTransaction];  int i = 0;  while (i++ < 20) {    [db executeUpdate:@"INSERT INTO TEST (name) values (?)" , [NSString stringWithFormat:@"number %d", i]];    if ([db hadError]) {      NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);    }  }  [db commit];  // SELECT  FMResultSet *rs = [db executeQuery:@"SELECT * FROM TEST"];  while ([rs next]) {    NSLog(@"%d %@", [rs intForColumn:@"id"], [rs stringForColumn:@"name"]);  }  [rs close];  [db close];}else{  NSLog(@"Could not open db.");}

接下来再看看用 DAO 的形式来访问数据库的使用方法,代码整体构造如下。

c1f50b99d8f378267cb330948da75adc.png

首先创建如下格式的数据库文件:

$ sqlite3 sample.dbsqlite> CREATE TABLE TbNote(   ...>  id INTEGER PRIMARY KEY,   ...>  title VARCHAR(255),   ...>  body VARCHAR(255)   ...> );

创建DTO(Data Transfer Object)

//TbNote.h#import @interface TbNote : NSObject {  int index;  NSString *title;  NSString *body;}@property (nonatomic, retain) NSString *title;@property (nonatomic, retain) NSString *body;- (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody;- (int)getIndex;@end//TbNote.m#import "TbNote.h"@implementation TbNote@synthesize title, body;- (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{  if(self = [super init]){    index = newIndex;    self.title = newTitle;    self.body = newBody;  }  return self;}- (int)getIndex{  return index;}- (void)dealloc {  [title release];  [body release];  [super dealloc];}@end

创建DAO(Data Access Objects)

这里将 FMDB 的函数调用封装为 DAO 的方式。

//BaseDao.h#import @class FMDatabase;@interface BaseDao : NSObject {  FMDatabase *db;}@property (nonatomic, retain) FMDatabase *db;-(NSString *)setTable:(NSString *)sql;@end//BaseDao.m#import "SqlSampleAppDelegate.h"#import "FMDatabase.h"#import "FMDatabaseAdditions.h"#import "BaseDao.h"@implementation BaseDao@synthesize db;- (id)init{  if(self = [super init]){    // 由 AppDelegate 取得打开的数据库    SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];    db = [[appDelegate db] retain];  }  return self;}// 子类中实现-(NSString *)setTable:(NSString *)sql{  return NULL;}- (void)dealloc {  [db release];  [super dealloc];}@end

下面是访问 TbNote 表格的类。

//TbNoteDao.h#import #import "BaseDao.h"@interface TbNoteDao : BaseDao {}-(NSMutableArray *)select;-(void)insertWithTitle:(NSString *)title Body:(NSString *)body;-(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body;-(BOOL)deleteAt:(int)index;@end//TbNoteDao.m#import "FMDatabase.h"#import "FMDatabaseAdditions.h"#import "TbNoteDao.h"#import "TbNote.h"@implementation TbNoteDao-(NSString *)setTable:(NSString *)sql{  return [NSString stringWithFormat:sql,  @"TbNote"];}// SELECT-(NSMutableArray *)select{  NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];  FMResultSet *rs = [db executeQuery:[self setTable:@"SELECT * FROM %@"]];  while ([rs next]) {    TbNote *tr = [[TbNote alloc]              initWithIndex:[rs intForColumn:@"id"]              Title:[rs stringForColumn:@"title"]              Body:[rs stringForColumn:@"body"]              ];    [result addObject:tr];    [tr release];  }  [rs close];  return result;}// INSERT-(void)insertWithTitle:(NSString *)title Body:(NSString *)body{  [db executeUpdate:[self setTable:@"INSERT INTO %@ (title, body) VALUES (?,?)"], title, body];  if ([db hadError]) {    NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);  }}// UPDATE-(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body{  BOOL success = YES;  [db executeUpdate:[self setTable:@"UPDATE %@ SET title=?, body=? WHERE id=?"], title, body, [NSNumber numberWithInt:index]];  if ([db hadError]) {    NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);    success = NO;  }  return success;}// DELETE- (BOOL)deleteAt:(int)index{  BOOL success = YES;  [db executeUpdate:[self setTable:@"DELETE FROM %@ WHERE id = ?"], [NSNumber numberWithInt:index]];  if ([db hadError]) {    NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);    success = NO;  }  return success;}- (void)dealloc {  [super dealloc];}@end

为了确认程序正确,我们添加一个 UITableView。使用 initWithNibName 测试 DAO。

//NoteController.h#import @class TbNoteDao;@interface NoteController : UIViewController {  UITableView *myTableView;  TbNoteDao *tbNoteDao;  NSMutableArray *record;}@property (nonatomic, retain) UITableView *myTableView;@property (nonatomic, retain) TbNoteDao *tbNoteDao;@property (nonatomic, retain) NSMutableArray *record;@end//NoteController.m#import "NoteController.h"#import "TbNoteDao.h"#import "TbNote.h"@implementation NoteController@synthesize myTableView, tbNoteDao, record;- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {  if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {    tbNoteDao = [[TbNoteDao alloc] init];    [tbNoteDao insertWithTitle:@"TEST TITLE" Body:@"TEST BODY"];//    [tbNoteDao updateAt:1 Title:@"UPDATE TEST" Body:@"UPDATE BODY"];//    [tbNoteDao deleteAt:1];    record = [[tbNoteDao select] retain];  }  return self;}- (void)viewDidLoad {  [super viewDidLoad];  myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];  myTableView.delegate = self;  myTableView.dataSource = self;  self.view = myTableView;}- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {  return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  return [record count];}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  static NSString *CellIdentifier = @"Cell";  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  if (cell == nil) {    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];  }  TbNote *tr = (TbNote *)[record objectAtIndex:indexPath.row];  cell.text = [NSString stringWithFormat:@"%i %@", [tr getIndex], tr.title];  return cell;}- (void)didReceiveMemoryWarning {  [super didReceiveMemoryWarning];}- (void)dealloc {  [super dealloc];}@end

最后我们开看看连接DB,和添加 ViewController 的处理。这一同样不使用 Interface Builder。

//SqlSampleAppDelegate.h#import @class FMDatabase;@interface SqlSampleAppDelegate : NSObject {  UIWindow *window;  FMDatabase *db;}@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) FMDatabase *db;- (BOOL)initDatabase;- (void)closeDatabase;@end//SqlSampleAppDelegate.m#import "SqlSampleAppDelegate.h"#import "FMDatabase.h"#import "FMDatabaseAdditions.h"#import "NoteController.h"@implementation SqlSampleAppDelegate@synthesize window;@synthesize db;- (void)applicationDidFinishLaunching:(UIApplication *)application {  if (![self initDatabase]){    NSLog(@"Failed to init Database.");  }  NoteController *ctrl = [[NoteController alloc] initWithNibName:nil bundle:nil];  [window addSubview:ctrl.view];  [window makeKeyAndVisible];}- (BOOL)initDatabase{  BOOL success;  NSError *error;  NSFileManager *fm = [NSFileManager defaultManager];  NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *documentsDirectory = [paths objectAtIndex:0];  NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];  success = [fm fileExistsAtPath:writableDBPath];  if(!success){    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];    success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];    if(!success){      NSLog([error localizedDescription]);    }    success = NO;  }  if(success){    db = [[FMDatabase databaseWithPath:writableDBPath] retain];    if ([db open]) {      [db setShouldCacheStatements:YES];    }else{      NSLog(@"Failed to open database.");      success = NO;    }  }  return success;}- (void) closeDatabase{  [db close];}- (void)dealloc {  [db release];  [window release];  [super dealloc];}@end


http://www.ppmy.cn/news/447291.html

相关文章

【备战秋招】每日一题:2023.05-B卷-华为OD机试 - 代码编辑器

为了更好的阅读体检&#xff0c;为了更好的阅读体检&#xff0c;&#xff0c;可以查看我的算法学习博客代码编辑器 题目描述 某公司为了更高效的编写代码&#xff0c;邀请你开发一款代码编辑器程序。 程序的输入为 已有的代码文本和指令序列&#xff0c;程序需输出编辑后的最…

Charles + iphone手机 抓取https包

1.下载 charles 2.安装 charles 3.mac配置charles 3.1>点击菜单 Help–>SSL Proxying–>Install Charles Root CertifiCate 3.2>在打开的对话框左边种类框种选择证书&#xff0c;右边右键点击charles的证书&#xff0c;在菜单中选择"显示简介" 3.3&…

我用ChatGPT写2023高考语文作文(七):上海卷

2023年 上海卷 适用地区&#xff1a;上海 一个人乐意去探索陌生世界&#xff0c;仅仅是因为好奇心吗&#xff1f;请写一篇文章&#xff0c;谈谈你对这个问题的认识和思考。 要求&#xff1a;(1&#xff09; 自拟题目&#xff1b;&#xff08;2&#xff09;不少于 800字。"…

3DMAX 的重要知识和插件介绍

四大渲染器的基本介绍 四大渲染器的基本介绍 Mental Ray&#xff08;简称MR&#xff09; Mental Ray是早期出现的两个重量级的渲染器之一&#xff08;另外一个是Renderman&#xff09;&#xff0c;为德国Mental Images公司的产品。在刚推出的时候&#xff0c;集成在著名的3D动…

【论文阅读】Weighted Boxes Fusion(WBF)模型融合原理解读

论文地址&#xff1a;https://arxiv.org/pdf/1910.13302.pdf 代码地址&#xff1a;GitHub - ZFTurbo/Weighted-Boxes-Fusion: Set of methods to ensemble boxes from different object detection models, including implementation of "Weighted boxes fusion (WBF)"…

python3GUI--图片浏览器By:PyQt5(附源码)

文章目录 一&#xff0e;前言二&#xff0e;展示1.主界面2.添加图片3.多级目录4.查看文件信息5.调整UI布局 三&#xff0e;源代码1.image_god_main_v.py2.image_god_GUI.py 四&#xff0e;总结 一&#xff0e;前言 本次使用PyQt5开发一款图片浏览器&#xff0c;本篇主要练习QD…

openstack部署手册[T版]

Openstack部署文档 步骤1&#xff1a;准备环境 1. 服务器硬件配置 controller 8G, 8CPU , 双网卡, 100G compute 4-8G, 4-8CPU, 双网卡 &#xff0c;40G 2. 配置阿里云yum源 curl -o /etc/yum. repos. d/CentOS-Base. repo http://mirrors. aliyun. com/repo/Centos-7. r…

华为C语言代码规范

https://blog.csdn.net/m0_38106923/article/details/105042594?utm_mediumdistribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9.nonecase&depth_1-utm_sourcedistribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9.nonecase