码迷,mamicode.com
首页 > 其他好文 > 详细

网络初级整理(一)

时间:2015-12-07 11:55:49      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

网络初级整理

1、KVC & KVO

1)、KVC

//KVC : 键值编码    Key Value Coding

- (id)initWithDictionary:(NSDictionary *)dic{

    if (self = [super init]) {

//        self.name = dic[@"name"];

//        self.idNum = dic[@"idnum"];

//        self.sex = dic[@"sex"];

//        self.faceValue = dic[@"facevalue"];

        for (NSString *key in dic) {

            [self setValue:dic[key] forKey:key];

        }

    }

    return self;

}

//容错

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

    NSLog(@"StudentUndefine:%@",key);

}

+(instancetype)studentWithDictionary:(NSDictionary *)dic{

    return [[Student alloc]initWithDictionary:dic];

}

 

//容错

-(void)setValue:(id)value forKey:(NSString *)key{

 

    [super setValue:value forKey:key];

}

 

2)、KVO

Key Value Observer 键值观察者模式

解耦和

addObserver:(观察者)ForKeyPath:(观察路径)options:(观察模式:New,Old)Context:nil

观察者:必须要实现下面的方法

一旦被观察者对应的路径的值发生改变,就会调用下面的方法

- (void)observeValueForKeyPath:(NSString *)keyPath(观察路径) ofObject:(id)object(被观察的对象) change:(NSDictionary *)change(改变的值:kind:0/1,old:老值,new:新值) context:(void *)context

 

2、JSON & XML

 

XML GData

 

工程配置

1)、XML_GData配置

3.1、将GData目录拉进解析工程

         3.2、工程 -> Build Phases -> Link Binary With Librarles -> + -> 搜索处输入:libxml2 -> 选择libxml2.dylib-> 点add

         3.3、工程 -> Build Setting -> All -> 搜索处输入:Header Search Paths -> 双击 Header Search Paths 的后面 -> 点+ /usr/include/libxml2 -> 点击空白处退出

         3.4、工程 -> Bulid Phases -> Compile Sources -> 双击GDataXMLNode.m 后空白处 -> 输入-fno-objc-arc -> 点击其他空白处退出

         3.5、导入#include "GDataXMLNode.h"

         3.6、编译

 

NSString *jsonStr = @"{\"name\":\"licheng\",\"info\":{\"number\":\"89757\",\"age\":\"21\"}}";

    /*

         1.josn:可读性差,兼容性差 :XML:可读性强,兼容性强

         2.josn:数据量大,解析相对简单 : XML:解析复杂

     */

    

    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

    

    

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

    NSLog(@"%@",dic);

 

 

 // 获取本地的XML文字信息

    NSString *path = [[NSBundle mainBundle]pathForResource:@"cate" ofType:@"txt"];

    NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",str);

    

    // GDataXMLDocument:想要解析需要先讲xml数据装入

    GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithXMLString:str options:0 error:nil];

    //initWithData:<#(NSData *)#> options:<#(unsigned int)#> error:<#(NSError *__autoreleasing *)#>

    // 获取所有的@"promotion"

    // 解析json一层一层解析

    NSArray *nodes = [document nodesForXPath:@"//promotion" error:nil];

    for (GDataXMLElement *element in nodes) {

        PromotionModel *model = [PromotionModel promotionModelWith:element];

        NSLog(@"%@",model.name);

    }

 

// 例子:取第一个节点的name值

//    GDataXMLElement *promotin = nodes[0];

//    NSArray *nameNodes = [promotin elementsForName:@"name"];

//    

//    GDataXMLElement *nameElement = nameNodes[0];

//    

//    // 关键字

//    NSString *namekey = [nameElement name];

//    // 值

//    NSString *nameValue = [nameElement stringValue];

//    

//    NSLog(@"%@",nameValue);

 

KissXML

- (void)analyzeXML

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil];

    

    NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    // 文件的存放位置:1.软件包中(bundle)2.沙盒3.内存4.intenet

    

    NSError *error = nil;

    

    DDXMLDocument *document = [[DDXMLDocument alloc]initWithXMLString:string options:0 error:&error];

    if (error != nil) {

        NSLog(@"%@",error.localizedDescription);

    }

    NSArray *nodes = [document nodesForXPath:@"//root" error:nil];

    DDXMLElement *element = [nodes firstObject];

    // 逐层取值

    DDXMLElement *nameElement = [[element elementsForName:@"CityName"] firstObject];

    // 根据目标路径取值

//    DDXMLElement *nameElement = [[element nodesForXPath:@"//CityName" error:nil] firstObject];

    NSLog(@"%@",[nameElement stringValue]);

}

 

JSON

/**

     *  1、json:字典模型的数据结构:转移字符串(哈希字串)流结构NSData

     *  2、转义字串

     *

     */

    NSString *jsonStr = @"{\"name\":\"张三\",\"age\":20,\"faceValue\":80}";

    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    NSLog(@"%@",dic);

 

 

3、NSURLSession  &  NSURLConnection

 

1)、NSURLSession

网络地址

NSString *urlString = @"http://pic.nipic.com/2007-11-09/200711912453162_2.jpg";

链接地址

    NSURL *url = [NSURL URLWithString:urlString];

    

单例的会话管理类

    NSURLSession *session = [NSURLSession sharedSession];

    

数据获取的权柄

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

网络访问是否出错

        if (error) {

打印错误描述

            NSLog(@"%@",error.localizedDescription);

        }else{

强转响应题

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

判断响应状态码

            if (httpResponse.statusCode == 200) {

 

                UIImage *image = [UIImage imageWithData:data];

                

本地持久化(写文件)

                NSString *path = [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),[response.URL lastPathComponent]];

                [data writeToFile:path atomically:YES];

                

                _imageView.image = image;

            }else{

                NSLog(@"%d",(int)httpResponse.statusCode);

            }

        }

    }];

    

    // 手动开始session下载

    [dataTask resume];

 

 

2)、NSURLConnection 

<NSURLConnectionDataDelegate>遵守协议

// 1.链接地址:URL

    // 2.请求:Request

    // 3.链接:Connection

    

    NSString *string = @"http://pic.nipic.com/2007-11-09/200711912453162_2.jpg";

    NSURL *url = [NSURL URLWithString:string];

    

    // 通过链接地址构建一个请求对象

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 通过一个请求构建一个链接,

    // delegate:代理用于返回数据

    // delegate:一旦设置,立即发起异步请求

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

 

三次握手

// 获得了服务器传回的消息

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;

    NSLog(@"%ld",httpRes.statusCode);

}

 

// 构建长链接后,开始接受数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_data appendData:data];

}

 

// 数据接收完成,挥手(断开长链接)

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    _imageView.image = [UIImage imageWithData:_data];

}

 

// 失败时调用

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%@",error.localizedDescription);

}

 

4、GET & POST

get <—>post

1.get一般是从服务器获取数据,Post常用来发送数据。

2.get把参数列表添加到Action的表单中(参数列表),参数和值一一对应,且容易辨识。post将表单当中的内容(body/header)传给服务器,传参内容看不到。

3.取值方式不同:get: Request.QueryString获取变量的值,post:Request.From获取

4.Get传输的数据小一般小于2KB,post较大不受限制,(IIS4:80KB,IIS5:100KB)

5.Get执行效率相对较高,但安全性查(太暴露)

 

建议:

get安全性差,有关安全的事情需要用post(注册登陆,发送用户信息)。

get效率高,获取简单的用户数据(修改,删除,添加用户信息时要用post)

 

同步 异步

 

1、 同步GET请求

//第一步,创建URL

NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

 

//第二步,通过URL创建网络请求

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

//NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)

其中缓存协议是个枚举类型包含:

NSURLRequestUseProtocolCachePolicy(基础策略)

NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)

NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)

NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)

NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)

NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)

//第三步,连接服务器

NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

 

NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

 

NSLog(@"%@",str);

 

 

2、同步POST请求

//第一步,创建URL

NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];

//第二步,创建请求

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

[request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET

NSString *str = @"type=focus-c";//设置参数

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];

//第三步,连接服务器

 

NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

 

NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

 

NSLog(@"%@",str1);

 

 

 

3、异步GET请求

//第一步,创建url

NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

//第二步,创建请求

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

//第三步,连接服务器

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

 

 

 

4、异步POST请求

//第一步,创建url

NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];

//第二步,创建请求

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

[request setHTTPMethod:@"POST"];

NSString *str = @"type=focus-c";

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];

//第三步,连接服务器

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

 

 

 

 

5、异步请求的代理方法

//接收到服务器回应的时候调用此方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

NSLog(@"%@",[res allHeaderFields]);

self.receiveData = [NSMutableData data];

 

}

//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

[self.receiveData appendData:data];

}

//数据传完之后调用此方法

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];

NSLog(@"%@",receiveStr);

}

//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法

-(void)connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error

{

NSLog(@"%@",[error localizedDescription]);

}

 

5、AFNETworking

1)、POST

NSString *path = @"http://10.0.176.193/iOS_PHP/login.php";

    // 实例化一个管理类

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    // 设置返回数据为二进制的流

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    [manager POST:path parameters:@"user=fenbingbing&password=123456" success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSLog(@"%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        

        NSLog(@"%@",error.localizedDescription);

        

    }];

2)、GET

NSString *path = @"http://www.baidu.com";

    //1.网络请求管理类

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    // 2.设置网络传输数据的类型为2进制

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    // 设置:可接受的数据类型 (content-type)(可选)

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    // 3.发送GET请求

    /**

        1.NSString: 接口路径

        2.附加信息:(参数列表)

        3.block:成功时会调用的

        4.block:失败时调用

     */

    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSString *string = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"%@",string);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        

    }];

3)、下载数据

//4.下载

- (void)download

{

    NSString *path = @"http://imgcache.qq.com/club/item/avatar/7/i87/all.zip";

    // 下载的管理类

    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    /**

        1.请求实体

        2.进度类地址(&progress)

        3.下载图片后,图片存放的地址

        4.下载成功后的操作

     */

    

    NSProgress *progress = nil;

    

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]] progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        

        // 获取沙盒路径

        NSString *path = [NSString stringWithFormat:@"%@/Documents/img.zip",NSHomeDirectory()];

        return [NSURL fileURLWithPath:path];

        

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        // 结束时调用

        NSLog(@"%@",error.localizedDescription);

    }];

    // 手动开启下载

    [downloadTask resume];

    

    //采用KVO的方式观察progress的变化

    [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

}

 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    // object:被观察的对象

    float value = [[object valueForKey:keyPath]floatValue];

    NSLog(@"%f",value);

}

4)、网络状态判断

 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    //reachabilityManager  网络连接能力的管理类

    // 当网络状态发生改变的时候调用此block

    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        /*

        AFNetworkReachabilityStatusUnknown          = -1, 不知道

        AFNetworkReachabilityStatusNotReachable     = 0,  不可达

         AFNetworkReachabilityStatusReachableViaWWAN = 1, 手机lan网路(2,3,4)G

        AFNetworkReachabilityStatusReachableViaWiFi  //Wifi

            */

       

        NSArray *array = @[@"不知道",@"不可达",@"3G",@"WiFi"];

        NSLog(@"%@",array[status + 1]);

        AppDelegate *appdele = APPDele;

        appdele.reachAbilety = status > 0;

 

        

//        switch (status) {

//            case AFNetworkReachabilityStatusNotReachable:

//            case AFNetworkReachabilityStatusUnknown:{

//                

//                AppDelegate *appdele = APPDele;

//                appdele.reachAbilety = NO;

//                break;

//            }

//            case AFNetworkReachabilityStatusReachableViaWiFi:

//            case AFNetworkReachabilityStatusReachableViaWWAN:

//            {

//                AppDelegate *appdele = APPDele;

//                appdele.reachAbilety = YES;

//                break;

//            }

//            default:

//                break;

//        }

        

    }];

    

    [manager.reachabilityManager startMonitoring];

 

6、ASINetworking ASIHTTPRequestDelegate

(libxml2   libz.1.2.5   MobileCoreServices  SystemConfiguration  CFNetwork) ASIHttpRequst

- (void)viewDidLoad {

    [super viewDidLoad];

    /**

     *  1、添加系统库

        2、添加系统库搜索路径

        3、添加ARC兼容

     */

//    [self ASIGet];

    [self ASIPost];

}

-(void)ASIGet{

    NSString *str = @"http://bea.wufazhuce.com/OneForWeb/one/getHp_N?strDate=2015-05-25&strRow=1";

    NSURL *url = [NSURL URLWithString:str];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    request.delegate = self;

    request.requestHeaders =[NSMutableDictionary dictionaryWithDictionary:@{@"123":@"456"}];

    

    [request startAsynchronous];

}

-(void)ASIPost{

    NSString *str = @"http://10.0.8.8/sns/my/user_list.php";

    NSURL *url = [NSURL URLWithString:str];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    request.requestMethod = @"POST";

    request.delegate = self;

    NSString *pramaList = @"page=1&number=20";

    

    NSData *data = [pramaList dataUsingEncoding:NSUTF8StringEncoding];

    request.postBody = [NSMutableData dataWithData:data];

    

    [request startAsynchronous];

}

 

-(void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{

//    NSLog(@"%@",request.requestHeaders);

//    NSLog(@"%@",responseHeaders);

}

/**

 *  请求结束

 */

-(void)requestFinished:(ASIHTTPRequest *)request{

    NSData *jsonData = request.responseData;

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

    NSLog(@"%@",dic);

}

 

 

 

 

7、系统调用相机  视频播放 音乐播放 录音

1)、遵守三个协议 <UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

 

//将图片保存到相册

-(void)saveImagrToAlbum

{

    /*

     1、保存的图片

     2、回调对象

     3、回调方法

     4、预留接口

     */

    UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"90.jpg"], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

}

 

调用的是系统的方法

- (void)               image: (UIImage *) image

    didFinishSavingWithError: (NSError *) error

                 contextInfo: (void *) contextInfo

{

    if (error) {

        NSLog(@"%@",error.localizedDescription);

    }

}

// 相册选择

- (void)viewPhotoInAlbum

{

    // 图片选择器(相册,相机(单张拍照))

    UIImagePickerController *picker = [[UIImagePickerController alloc]init];

    picker.delegate = self;

    /*UIImagePickerControllerSourceTypePhotoLibrary,// 相册

    UIImagePickerControllerSourceTypeCamera,//相机

     */

    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:nil];

}

 

// 拍照获取

- (void)takePhoto{

    //isSourceTypeAvailable: 系统是否允许调用:调用类型

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){

        UIImagePickerController *picker = [[UIImagePickerController alloc]init];

        picker.delegate = self;

        picker.sourceType = UIImagePickerControllerSourceTypeCamera;

        // 允许编辑

        picker.allowsEditing = YES;

        [self presentViewController:picker animated:YES completion:nil];

    }else{

        NSLog(@"系统不让用");

    }

}

 

// 点击了某一张图片

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {

        

    }else{

        UIImage *image = info[UIImagePickerControllerOriginalImage];

        [_imageBtn setBackgroundImage:image forState:UIControlStateNormal];

        [picker dismissViewControllerAnimated:YES completion:nil];

    }

}

 

2)、系统的音乐播放器AVAudioPlayer

 导入 AVFoundation.framework

遵守AVAudioPlayerDelegate协议

 

 

_musicPlayer = nil;

    

    _titleLabel.text = _namaArray[index];

    

    _musicPlayer = [[AVAudioPlayer alloc]initWithData:_dataArray[index] error:nil];

    _musicPlayer.delegate = self;

    

    _songDuration = _musicPlayer.duration;

    

     // 准备播放

    [_musicPlayer prepareToPlay];

    _isChange = NO;

     // 播放

    _playBtn.selected = YES;

    [_musicPlayer play];

 

#pragma mark- AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{

    if (_playRandom) {

        [self playAtRandom];

    }else{

        _isChange = YES;

        self.playIndex++;

    }

}

 

 

3)、系统的视频播放器  MPMoviePlayerViewController

导入 AVFoundation.framework &MediaPlayer.framework &CoreMedia.framework

 

NSURL *url = [[NSBundle mainBundle]URLForResource:@"dzs" withExtension:@"mp4"];

    _mov = [[MPMoviePlayerViewController alloc]initWithContentURL:url];

    

    _mov.moviePlayer.movieSourceType = MPMovieSourceTypeFile;

    [_mov.moviePlayer play];

    

    [self presentMoviePlayerViewControllerAnimated:_mov];

 

8、CoreData

1.数据库

1).按照数据结构来组织、存储和管理数据的仓库

 

2).数据库的作用

存储数据

组织和管理数据

 

3).关系型数据库      关联模型数据库

用二维表格来表?复杂的数据关系

 

4).SQLite数据库,MySQL,SQLServer,Orcle

轻量级的关系型数据库

设计之初就是针对嵌?式做的

iOS和Android都是?的SQLite

 

5).SQLite支持的数据类型

NULL - 空值

INTERGER - 有符号整数类型

REAL - 浮点数类型

TEXT - 字符串(其编码取决于DB的编码) 

BLOB - 二进制表?示

 

 

 

 

==================================

2.SQL语句,结构化查询语言(Structured Query Language),专?用作数据库操作的语言,官?推荐关键字?写

1).建表语句

create table if not exists TableName(Field1 DataType, Field2 Data, ...)

 

2).插入语句

insert into TableName(Field1, Field2, ...) values(value1, value2, ...)

 

3).更新数据

update TableName set Field1=Value1, Field2=Value2    【WHERE …..条件语句】

 

4).删除数据

delete from TableName     【WHERE …..条件语句】

 

 

5).查询语句

select Field from TableName // 查询指定字段数据

 

select * from TableName limit 10 // 查询所有数据并且取最后10条数据

 

select * from TableName order by Field asc // 查询结果根据哪个字段来排排序(asc升序/desc降序)

 

select count (*) from TableName // 查询数据的数量

 

6).条件判断

select * from TableName where Field=Value   // 等于

where Field>Value   // 大于

where Field<Value   // 小于

where Field<>Value // 不等于

 

where Field in (‘Value1‘, ‘Value2‘, ‘Value3‘) // 在集合中的?个

where Field between Value1 and Value2  // 在两个值之间

 

 

 

==================================

3.FMDB,SQLite数据库原?的接口是C语言的,iOS开发中,几乎都是?FMDB来管理SQLite数据库

1).创建数据库(已经存在就不创建了)

+ databaseWithPath:

 

2).打开关闭数据库

- open

- close

 

3).执行SQL语句

- executeUpdate  // 非查询的SQL,都是用这个执行

- executeQuery   // 查询的SQL

 

4).查询结果集,FMResultRet

遍历

- next // 执?行?一次,指针就会移动到下?一条记录

 

当前记录操作

- stringForColumn: // 根据字段名,取出值,并转成String

- stringForColumnIndex: // 根据字段下标,取出值,并转成String

 

 

//新建或打开数据库,

//创建数据表,

//插入数据,

//查询数据并打印

//2、sqlite 的方法

//sqlite3          *db, 数据库句柄,跟文件句柄FILE很类似

//sqlite3_stmt      *stmt, 这个相当于ODBC的Command对象,用于保存编译好的SQL语句

//sqlite3_open(),   打开数据库,没有数据库时创建。

//sqlite3_exec(),   执行非查询的sql语句

//Sqlite3_step(),  在调用sqlite3_prepare后,使用这个函数在记录集中移动。 while(sqlite3_step(statement)==SQLITE_ROW)

{}I

//Sqlite3_close(), 关闭数据库文件

//还有一系列的函数,用于从记录集字段中获取数据,如

//sqlite3_column_text(), 取text类型的数据。

//sqlite3_column_blob(),取blob类型的数据

//sqlite3_column_int(), 取int类型的数据

 

网络初级整理(一)

标签:

原文地址:http://www.cnblogs.com/LPP-521/p/5025465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!