热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Iphone中Sqlite的使用

Sqlite的访问:NoteSqlite:1#import<FoundationFoundation.h>2@classSqliteEntit

Sqlite的访问:

NoteSqlite:

 1 #import 
 2 @class SqliteEntity;
 3 #import "sqlite3.h"
 4 
 5 @interface NoteSqlite : NSObject{
 6     NSString *databaseName;  //操作的数据库名
 7     NSString *TableName;    //操作的表名
 8     sqlite3 *database;
 9     sqlite3_stmt *statement;
10     char *errorMsg;     //错误信息
11     SqliteEntity *entitys;
12 }
13 
14 @property (nonatomic,retain) NSString *_Execsql;
15 @property (nonatomic,retain) NSString *TableName;
16 @property (nonatomic,retain) NSString *databaseName;
17 
18 //打开数据库
19 -(BOOL)Open;
20 //关闭数据库
21 -(BOOL)Close;
22 
23 //创建表
24 -(BOOL)create;
25 
26 //增加、删除、修改、查询
27 -(BOOL)insertDataForSql;
28 -(BOOL)deleteAll;
29 -(BOOL)deleteDataForSql;
30 -(BOOL)updateDataForSql;
31 
32 -(SqliteEntity *)selectAll;
33 -(NSMutableArray *)selectForSql;
34 
35 @end
View Code
  1 #import "NoteSqlite.h"
  2 #import "SqliteEntity.h"
  3 
  4 @implementation NoteSqlite
  5 
  6 - (id)init
  7 {
  8     self = [super init];
  9     return self;
 10 }
 11 
 12 //打开数据库
 13 -(BOOL)Open{
 14     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
 15     NSString *documentsDirectory=[paths objectAtIndex:0];
 16     NSString *path=[documentsDirectory stringByAppendingPathComponent:databaseName];
 17     NSFileManager *fileManger=[NSFileManager defaultManager];
 18     BOOL find=[fileManger fileExistsAtPath:path];
 19     //判断文件是否存在
 20     if (find) {
 21         NSLog(@"数据库文件已经存在");
 22         //打开数据库、返回操作是否正确
 23         if(sqlite3_open([path UTF8String], &database)==SQLITE_OK){
 24             NSLog(@"成功打开数据库");
 25         }
 26         return YES;
 27     }else{
 28         if(sqlite3_open([path UTF8String], &database)==SQLITE_OK){
 29             //调用createMusicList创建数据库和表
 30             [self create];
 31             return YES;
 32         }else{
 33             sqlite3_close(database);
 34             NSLog(@"Error:open database file.");
 35             return NO;
 36         }
 37         return NO;
 38     }
 39 }
 40 
 41 //创建表
 42 -(BOOL)create{
 43     if ([self ExecSql]) {
 44         NSLog(@"create Ok.");
 45         return YES;
 46     }
 47     return NO;
 48 }
 49 
 50 #pragma mark --新增、删除、修改、查询
 51 -(BOOL)insertDataForSql{
 52     if ([self ExecSql]) {
 53         NSLog(@"Insert Ok.");
 54         return YES;
 55     }
 56     return NO;
 57 }
 58 
 59 -(BOOL)deleteAll{
 60     self._Execsql=[NSString stringWithFormat:@"Delete from %@",_TableName];
 61     if ([self ExecSql]) {
 62         NSLog(@"Delete All Ok");
 63         return YES;
 64     }
 65     return NO;
 66 }
 67 
 68 -(BOOL)deleteDataForSql{
 69     if ([self ExecSql]) {
 70         NSLog(@"Delete Ok");
 71         return YES;
 72     }
 73     return NO;
 74 }
 75 
 76 -(BOOL)updateDataForSql{
 77     if ([self ExecSql]) {
 78         NSLog(@"Update Ok");
 79         return YES;
 80     }
 81     return NO;
 82 }
 83 
 84 -(NSMutableArray *)selecteAll{
 85     self._Execsql=[NSString stringWithFormat:@" select * from %@",TableName];
 86     entitys.array= [self ExecSlect];
 87     return entitys.array;
 88 }
 89 
 90 -(NSMutableArray *)selectForSql{
 91     entitys.array= [self ExecSlect];
 92     return entitys.array;
 93 }
 94 
 95 
 96 #pragma mark --sql语句执行(Insert,Update,delete)
 97 -(BOOL)ExecSql{
 98     const char *execsql=[self._Execsql UTF8String];
 99     if (sqlite3_exec(database, execsql, NULL, NULL, &errorMsg)==SQLITE_OK) {
100         NSLog(@"执行语句成功");
101         return YES;
102     }
103     NSLog(@"Error : %s",errorMsg);
104     sqlite3_free(errorMsg);
105     return NO;
106 }
107 
108 #pragma mark --Sql语句查询
109 -(NSMutableArray *)ExecSlect{
110     
111     entitys=[[[SqliteEntity alloc]init]autorelease];
112     entitys.array=[NSMutableArray arrayWithCapacity:6];
113     
114     const char *selectstr=[self._Execsql UTF8String];
115     if (sqlite3_prepare_v2(database, selectstr, -1, &statement, Nil)==SQLITE_OK) {
116         NSLog(@"SELECT OK");
117         //添加返回的数据
118         while (sqlite3_step(statement)==SQLITE_ROW) {
119             SqliteEntity *entity=[[SqliteEntity alloc]init];
120             
121             entity.catid=sqlite3_column_int(statement, 0);
122             entity.parentid=sqlite3_column_int(statement, 1);
123             entity.ordering=sqlite3_column_int(statement, 4);
124             
125             entity.title=[NSString stringWithCString:(char *)sqlite3_column_text(statement, 2) encoding:NSUTF8StringEncoding];
126             entity.entrytype=[NSString stringWithCString:(char *)sqlite3_column_text(statement, 3) encoding:NSUTF8StringEncoding];
127             
128             //字符串格式化和截取
129             //NSDateFormatter *fomater=[[NSDateFormatter alloc]init];
130             //[fomater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
131             //NSData *ndate=[[fomater dateFromString:[entity.title substringToIndex:[entity.title length-5]]];
132             
133             //添加数据集
134             
135             
136             NSMutableDictionary *dic=  [NSMutableDictionary dictionaryWithObjectsAndKeys:
137                                         [NSString stringWithFormat:@"%d",entity.catid],@"catid",
138                                         [NSString stringWithFormat:@"%d",entity.parentid],@"parentid",
139                                         entity.title,@"title",
140                                         entity.entrytype,@"entrytype",
141                                         [NSString stringWithFormat:@"%d",entity.ordering],@"ordering",nil];
142             
143             [entitys.array insertObject:dic atIndex:[entitys.array count]];
144                         
145             [entity release];
146         }
147         return entitys.array;
148     }
149     return entitys.array;
150 }
151 
152 
153 @end
View Code

SqliteEntity:

 1 #import 
 2 
 3 @interface SqliteEntity : NSObject
 4 
 5 @property(nonatomic,readwrite) int catid;
 6 @property(nonatomic,readwrite) int parentid;
 7 @property(nonatomic,retain) NSString *title;
 8 @property(nonatomic,retain) NSString *entrytype;
 9 @property(nonatomic,readwrite) int ordering;
10 @property(nonatomic,assign) NSMutableArray *array;  //返回从数据库中取到的数据集
11 @end
View Code

Sqlite访问测试:

 1 #import 
 2 #import "NoteSqlite.h"
 3 
 4 @interface DatabaseViewController : UITableViewController{
 5     NoteSqlite *sqlite;
 6     SqliteEntity *entity;
 7     NSMutableArray *DataList;
 8 }
 9 
10 @end
View Code
  1 //
  2 //  DatabaseViewController.m
  3 //  UserSQLite
  4 //
  5 //  Created by Liaoyang on 13-10-5.
  6 //  Copyright (c) 2013年 Liaoyang. All rights reserved.
  7 //
  8 
  9 #import "DatabaseViewController.h"
 10 #import "NoteSqlite.h"
 11 #import "SqliteEntity.h"
 12 #import "DetilViewController.h"
 13 
 14 @interface DatabaseViewController ()
 15 
 16 @end
 17 
 18 @implementation DatabaseViewController
 19 
 20 - (id)initWithStyle:(UITableViewStyle)style
 21 {
 22     self = [super initWithStyle:style];
 23     if (self) {
 24         //读取数据库,准备好数据信息
 25         
 26         sqlite=[[NoteSqlite alloc]init];
 27         sqlite.databaseName=@"IphoneDb";
 28         //创建表sql
 29         sqlite._Execsql=@"create table MenuItems (catid int(5),parentid int(5),title varchar(32),entrytype varchar(12),ordering int(5))";
 30         
 31         [sqlite Open];      //打开数据库(或创建数据库)
 32         
 33         sqlite.TableName=@"MenuItems";
 34         
 35         if ([sqlite create]) {
 36             [sqlite deleteAll];
 37             //插入数据
 38             sqlite._Execsql=@"insert into MenuItems (catid,parentid,title,entrytype,ordering) values (1,0,'First','category',1),(2,0,'Third','categroy',3),(3,0,'Second','categroy',2),(4,2,'Submenu','category',1),(5,0,'Action #1','result',4),(6,1,'Action #1B','result',1) ";
 39             //数据插入
 40             [sqlite insertDataForSql];
 41         }
 42         
 43         sqlite._Execsql=@"select * from MenuItems where parentid=0 order by ordering asc";
 44         DataList= [sqlite selectForSql];
 45         if ([DataList count]>0) {   //将表格下移动
 46             CGPoint tablecenter=self.view.center;
 47             self.view.center=CGPointMake(tablecenter.x, tablecenter.y+22);
 48             [DataList retain];
 49         }
 50     }
 51     return self;
 52 }
 53 
 54 - (void)viewDidLoad
 55 {
 56     [super viewDidLoad];
 57 
 58 }
 59 
 60 - (void)didReceiveMemoryWarning
 61 {
 62     [super didReceiveMemoryWarning];
 63     // Dispose of any resources that can be recreated.
 64 }
 65 
 66 #pragma mark - Table view data source
 67 
 68 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 69 {
 70     return 1;
 71 }
 72 
 73 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 74 {
 75     return [DataList count];
 76 }
 77 
 78 -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
 79     return @"GetDataBase";
 80 }
 81 
 82 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 83 {
 84     static NSString *CellIdentifier = @"Cell";
 85     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 86     if (cell == nil) {
 87         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
 88     }
 89     
 90     cell.textLabel.text=[[DataList objectAtIndex:indexPath.row]objectForKey:@"title"];
 91     if ([DataList objectAtIndex:indexPath.row]) {
 92         cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
 93     }
 94     
 95     return cell;
 96 }
 97 
 98 #pragma mark - Table view delegate
 99 
100 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
101 {
102     entity=[DataList objectAtIndex:indexPath.row];
103     DetilViewController *detail= [[DetilViewController alloc] init];
104      detail.title=[[DataList objectAtIndex:indexPath.row]objectForKey:@"title"];
105     
106     [self.view addSubview:detail.view];
107     [self.navigationController pushViewController:detail animated:YES];
108     [detail release];
109          
110 }
111 
112 @end
View Code

 


推荐阅读
  • ALTERTABLE通过更改、添加、除去列和约束,或者通过启用或禁用约束和触发器来更改表的定义。语法ALTERTABLEtable{[ALTERCOLUMNcolu ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • Java String与StringBuffer的区别及其应用场景
    本文主要介绍了Java中String和StringBuffer的区别,String是不可变的,而StringBuffer是可变的。StringBuffer在进行字符串处理时不生成新的对象,内存使用上要优于String类。因此,在需要频繁对字符串进行修改的情况下,使用StringBuffer更加适合。同时,文章还介绍了String和StringBuffer的应用场景。 ... [详细]
  • 本文讨论了在数据库打开和关闭状态下,重新命名或移动数据文件和日志文件的情况。针对性能和维护原因,需要将数据库文件移动到不同的磁盘上或重新分配到新的磁盘上的情况,以及在操作系统级别移动或重命名数据文件但未在数据库层进行重命名导致报错的情况。通过三个方面进行讨论。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • Python SQLAlchemy库的使用方法详解
    本文详细介绍了Python中使用SQLAlchemy库的方法。首先对SQLAlchemy进行了简介,包括其定义、适用的数据库类型等。然后讨论了SQLAlchemy提供的两种主要使用模式,即SQL表达式语言和ORM。针对不同的需求,给出了选择哪种模式的建议。最后,介绍了连接数据库的方法,包括创建SQLAlchemy引擎和执行SQL语句的接口。 ... [详细]
  • 本文讨论了在使用sp_msforeachdb执行动态SQL命令时,当发生错误时如何捕获数据库名称。提供了两种解决方案,并介绍了如何正确使用'?'来显示数据库名称。 ... [详细]
  • WhenIusepythontoapplythepymysqlmoduletoaddafieldtoatableinthemysqldatabase,itdo ... [详细]
  • PDO MySQL
    PDOMySQL如果文章有成千上万篇,该怎样保存?数据保存有多种方式,比如单机文件、单机数据库(SQLite)、网络数据库(MySQL、MariaDB)等等。根据项目来选择,做We ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • 本文详细介绍了MysqlDump和mysqldump进行全库备份的相关知识,包括备份命令的使用方法、my.cnf配置文件的设置、binlog日志的位置指定、增量恢复的方式以及适用于innodb引擎和myisam引擎的备份方法。对于需要进行数据库备份的用户来说,本文提供了一些有价值的参考内容。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • Oracle10g备份导入的方法及注意事项
    本文介绍了使用Oracle10g进行备份导入的方法及相关注意事项,同时还介绍了2019年独角兽企业重金招聘Python工程师的标准。内容包括导出exp命令、删用户、创建数据库、授权等操作,以及导入imp命令的使用。详细介绍了导入时的参数设置,如full、ignore、buffer、commit、feedback等。转载来源于https://my.oschina.net/u/1767754/blog/377593。 ... [详细]
author-avatar
jhb852
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有