博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SQLite数据库使用
阅读量:5021 次
发布时间:2019-06-12

本文共 4029 字,大约阅读时间需要 13 分钟。

SQLite是一个小型的关系数据库,支持事务(原子性 atomicity、一致性Con sistency、隔离性Isolation和持久性Durability)简称ACID,触发器和大多数复杂的查询。使用方式:1、在命令行下或客户端软件如SQLite Database Browser工具创建所需要的数据表和默认数据,创建的文件为*.sqlite3文件,并将该文件引入到xcode的工程中。2、在项目中配置SQLite的支持。   1)选择项目的根目录。   2)切换到 “Build Phases”标签下,展开“Link Binary With Libraries”。   3)点击加号按钮,选择“libsqlite3.dylib”,将该文件拖到Frameworks组下,即可使用SQLite。3、初始化数据连接:// 数据库连接static sqlite3 *database;// 打开数据库(单例)+ (id) singleton{	return [[[self alloc] init] autorelease];}-(id) init{	if ((self=[super init]) ) {		if (database == nil)		{      [self createEditableCopyOfDatabaseIfNeeded];			[self initDatabaseConnection];		}	}		return self;}// Creates a writable copy of the bundled default database in the application Documents directory.- (void) createEditableCopyOfDatabaseIfNeeded{    // First, test for existence.    NSFileManager *fileManager = [NSFileManager defaultManager];	    NSString *writableDBPath = [self sqliteDBFilePath];    // NSLog(@"%@", writableDBPath);    if ([fileManager fileExistsAtPath: writableDBPath])	{		return;	}	    // The writable database does not exist, so copy the default to the appropriate location.    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kSQLiteFileName];    NSError *error;    	if (![fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error])	{        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);    }}// 数据库文件路径- (NSString *) sqliteDBFilePath{		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dblite.sqlite3"];	NSLog(@"path = %@", path);		return path;}// 初始化数据库连接,打开连接,并返回数据库连接(存放在database中)- (void) initDatabaseConnection{	    if (sqlite3_open([[self sqliteDBFilePath] UTF8String], &database) != SQLITE_OK)	{        sqlite3_close(database);        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));    }}4、数据的增删改:+ (void) editAlbum: (Album *) album{    sqlite3_stmt *statement;        static char *sql = "UPDATE album SET title = ? WHERE albumid = ?";    //static char *sql = "INSERT INTO album (albumid,title) VALUES (NULL,?)";    // static char *sql = "DELETE FROM album WHERE albumid = ?";        if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)    {        NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(kAlbumDatabase));    }    sqlite3_bind_text(statement, 1, [album.title UTF8String], -1, NULL);    sqlite3_bind_int(statement, 2, album.albumid);        if (sqlite3_step(statement) == SQLITE_ERROR)    {        NSAssert1(0, @"Error: failed to edit album with message '%s'.", sqlite3_errmsg(kAlbumDatabase));    }        sqlite3_finalize(statement);}5、数据的查询:+ (NSMutableArray *) fetchAlbums{    NSMutableArray *albums = [NSMutableArray array];    	// Compile the query for retrieving data.	if (fetchAlbumsStatement == nil) {		const char *sql = "SELECT albumid, title FROM album";		if (sqlite3_prepare_v2(kAlbumDatabase, sql, -1, &fetchAlbumsStatement, NULL) != SQLITE_OK) {			NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(kAlbumDatabase));		}	}		while (sqlite3_step(fetchAlbumsStatement) == SQLITE_ROW)	{		Album *_album = [[Album alloc] init];                _album.albumid = sqlite3_column_int(fetchAlbumsStatement, 0);        _album.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(fetchAlbumsStatement, 1)];				[albums addObject:_album];        [_album release];	}		// Reset the statement for future reuse.	sqlite3_reset(fetchAlbumsStatement);        return albums;}6、关闭数据库:// 关闭数据库连接- (void) closeDatabase{  if (sqlite3_close(database) != SQLITE_OK)	{      NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));  }}

 

转载于:https://www.cnblogs.com/forrestblog/p/5077510.html

你可能感兴趣的文章
HDU 1856
查看>>
课堂作业01--架构师的职责
查看>>
iOS计算富文本(NSMutableAttributedString)高度
查看>>
2017/09/15 ( 框架2)
查看>>
SQL中join的用法
查看>>
dapper使用时性能优化
查看>>
【从数据库反向生成实体类】
查看>>
mybatis 批量更新 报错
查看>>
start WampServer如何关闭浏览目录
查看>>
PAT 甲级 1007 Maximum Subsequence Sum
查看>>
#Leetcode# 3. Longest Substring Without Repeating Characters
查看>>
HDU 2014 青年歌手大奖赛_评委会打分
查看>>
ie下警告console未定义
查看>>
STM32加密擦除
查看>>
Façade(Chapter 10 of Pro Objective-C Design Patterns for iOS)
查看>>
浅谈Java的学习之路——怎样学好JAVA ?
查看>>
常用正则表达式语法
查看>>
iOS中使用RSA加密
查看>>
codeforces 446A DZY Loves Sequences
查看>>
Android四个基本组件(2)之Service 服务与Content Provider内容提供商
查看>>