您的位置:首页 > 数据库

【iOS知识学习】_iOS下SQLite的使用

2012-10-31 15:48 417 查看
SQLite是嵌入式的和轻量级的sql数据库。广泛用于包括浏览器、ios、android以及一些便携需求的小型web应用系统。
SQLite是MySQL的精简版,无需服务器就能进行;限制条件:必须手动创建数据库,没有面向对象的接口;
Demo做了个简单的保存学生信息的例子,点击保存按钮可以保存信息,点击查询可以查询信息,Demo下载地址:http://download.csdn.net/detail/weasleyqi/4706760



要想在工程中使用SQLite,需要将SQLite的库添加到工程:



在本工程中的.h文件中引用这个库:
#import "sqlite3.h"

创建数据库:
接下来如果该数据库不存在需要创建这个数据库,创建的过程写在viewDidLoad里面:
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    NSString *docsDir;
    NSArray *dirPaths;
    
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    
    databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"info.db"]];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    if ([filemanager fileExistsAtPath:databasePath] == NO) {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {
            char *errmsg;
            const char *createsql = "CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY AUTOINCREMENT, NUM TEXT, CLASSNAME TEXT,NAME TEXT)";
            if (sqlite3_exec(dataBase, createsql, NULL, NULL, &errmsg)!=SQLITE_OK) {
                status.text = @"create table failed.";
            }
        }
        else {
            status.text = @"create/open failed.";
        }
    }
}
因为SQLite数据库是文件数据库,是保存在文件系统中的,ios下:

Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除

我们的数据库文件是保存在Documents下的。
切记,因为用的是C语法,sqlite3_open传入的是database的地址!

保存信息:
- (IBAction)saveinfo:(id)sender {
    sqlite3_stmt *statement;
    
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {
        if ([num.text isEqualToString:@""]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"SORRY!" message:@"number cannot be nil!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
        else {
        
        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO INFO (num,classname,name) VALUES(\"%@\",\"%@\",\"%@\")",num.text,classname.text,name.text];
        const char *insertstaement = [insertSql UTF8String];
        sqlite3_prepare_v2(dataBase, insertstaement, -1, &statement, NULL);
        if (sqlite3_step(statement)==SQLITE_DONE) {
            status.text = @"save to DB.";
            num.text = @"";
            classname.text = @"";
            name.text = @"";
        }
        else {
            status.text = @"save failed!";
        }
        sqlite3_finalize(statement);
        sqlite3_close(dataBase);
        }
    }
}


在往数据库里面插入数据的时候,我们需要先打开数据库,然后执行插入语句,结束的时候切记要关闭数据库!





查询操作:

- (IBAction)searchResult:(id)sender {
    const char *dbpath = [databasePath UTF8String];
    
    sqlite3_stmt *statement;
    
    if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {
        NSString *querySQL = [NSString stringWithFormat:@"SELECT classname,name from info where num=\"%@\"",num.text];
        const char *querystatement = [querySQL UTF8String];
        if (sqlite3_prepare_v2(dataBase, querystatement, -1, &statement, NULL)==SQLITE_OK) {
            if (sqlite3_step(statement)==SQLITE_ROW) {
                NSString *classnameField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
                classname.text = classnameField;
                NSString *nameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
                name.text = nameField;
                
                status.text = @"find~~~";                
            }
            else {
                status.text = @"did not find you need.";
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(dataBase);
    }
}


查询操作同样也是需要先打开数据库,再查询,最后关闭数据库,在这里就指定了根据学号来查询,其他情况未涉及。



在本例中还涉及一个触摸屏幕来关闭键盘:
在viewcontroller.h中添加申明代码:
- (IBAction)backgroundTap:(id)sender;
通过触摸屏幕来关闭键盘需要我们的.xib文件的class为UIControl,点击viewController.xib文件,选中view,打开 Identity Inspector,在class中选择UIConrol,再选择Connector
Inspector,找到Touch Down,把圆圈中的线映射到刚刚的IBAction;



在viewController.m文件中实现该方法:
- (IBAction)backgroundTap:(id)sender {
    [num resignFirstResponder];
    [classname resignFirstResponder];
    [name resignFirstResponder];
}
这样,基本上就完成了,代码的下载地址:http://download.csdn.net/detail/weasleyqi/4706760
希望对大家有帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: