您的位置:首页 > 数据库

SQLite3

2016-01-22 09:50 453 查看
数据库增删改查的基本sql语法略........  直接进入SQLite3的使用。

SQLite3常用函数:

1、打开数据库连接

int sqlite3_open(

const char *filename,  /* 数据库文件名(UTF-8)*/

sqlite3 **ppDb /* OUT: SQLite 数据库句柄 */

);

2、关闭数据库

int sqlite3_close(sqlite3*); //参数数据库句柄。

3、sqlite3_exec()可以执行任何SQL语句,比如创表、更新、插入和删除操作。但是一般不用它执行查询语句,因为它不会返回查询到的数据

int sqlite3_exec(

sqlite3*, /* 已经打开的数据库句柄 */

const char *sql,  /* 要执行的Sql语句  可以包括事务("BEGIN TRANSACTION")、回滚("ROLLBACK")和提交("COMMIT")*/

sqlite_callback,  /* 回调函数*/

void *,  /*传递给回调函数的参数*/

char **errmsg /* 保存错误信息*/

);

4、sql语句准备函数

int sqlite3_prepare_v2(

  sqlite3 *db,            /* 已经打开的数据库句柄 */

  const char *zSql,       /* 要执行的Sql语句  , UTF-8 encoded */

  int nByte,              /* 如果nByte小于0,则函数取出zSql中从开始到第一个0终止符的内容;如果nByte不是负的,那么它就是这个函数能从zSql中读取的字节数的最大值。如果nBytes非负,zSql在第一次遇见’/000/或’u000’的时候终止 */

  sqlite3_stmt **ppStmt,  /*上面提到zSql在遇见终止符或者是达到设定的nByte之后结束,假如zSql还有剩余的内容,那么这些剩余的内容被存放到pZTail中,不包括终止符*/

  const char **pzTail     /* 能够使用sqlite3_step()执行的编译好的准备语句的指针,如果错误发生,它被置为NULL,如假如输入的文本不包括sql语句。调用过程必须负责在编译好的sql语句完成使用后使用sqlite3_finalize()删除它 */

);

5、sqlite3_bind_text(

  sqlite3_stmt*,  /* 已经打开的数据库句柄 */

 int,    /* 占位符的位置,第一个占位符的位置是1,不是0 */

 const char*,   /* 占位符要绑定的值 */

 int,   /* 指在第3个参数中所传递数据的长度,对于C字符串,可以传递-1代替字符串的长 */

 void(*)(void*)  /* 可选的函数回调,一般用于在语句执行后完成内存清理工作*/

 );

6、sqlite_step():执行SQL语句,返回SQLITE_DONE代表成功执行完毕

7、sqlite3_free(char **errmsg)功能:释放存放错误信息的内存空间

8、sqlite_finalize():销毁sqlite3_stmt *对象

9、int sqlite3_get_table执行Sql查询,执行一次查询Sql 并且返回得到一个记录集。

int sqlite3_get_table(

  sqlite3*,              /* 已经打开的数据库句柄 */

  const char *sql,       /* 要执行的Sql语句*/

  char ***resultp,       /* 保存返回记录集的指针,包含列名及烈属性值。行优先,从0起计数下标*/

  int *nrow,             /*返回记录行数数*/

  int *ncolumn,          /* 返回记录列数*/

  char **errmsg          /* 返回错误信息*/

  )

10、void sqlite3_free_table(char **result); 释放当前查询的记录集所占用的内存

占位插入例子:

[objc] view
plaincopy

charchar *sql = "insert into t_person(name, age) values(?, ?);";  

sqlite3_stmt *stmt;  

if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {  

    sqlite3_bind_text(stmt, 1, "小明", -1, NULL);  

    sqlite3_bind_int(stmt, 2, 27);  

}  

if (sqlite3_step(stmt) != SQLITE_DONE) {  

    NSLog(@"插入数据错误");  

}  

sqlite3_finalize(stmt);  

查询例子:

[objc] view
plaincopy

const charchar *sql = "select name,price from t_shop";  

    sqlite3_stmt *stmt = NULL;  

    int status = sqlite3_prepare_v2(self.db, sql , -1, &stmt, NULL);  

    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确  

        while (sqlite3_step(stmt) == SQLITE_ROW) {// 成功取出一条数据  

           const  charchar *name = (const  charchar *)sqlite3_column_text(stmt, 0);  

           const  charchar *price = (const  charchar *)sqlite3_column_text(stmt, 1);  

            NSString name = [NSString stringWithUTF8String:name];  

            NSString price = [NSString stringWithUTF8String:price];  

        }  

          

    }  

2.实战案例:输入商品、价格,添加插入一条记录显示在table中,也可以查询。



1.项目引入libsqlite3



2.代码:

[objc] view
plaincopy

//  

//  ViewController.m  

//  sqlite  

//  

//  

  

#import "ViewController.h"  

#import <sqlite3.h>  

#import "ZXHShop.h"  

  

@interface ViewController ()<UITableViewDataSource,UISearchBarDelegate>  

@property (weak, nonatomic) IBOutlet UITextField *nameField;  

@property (weak, nonatomic) IBOutlet UITextField *priceFIeld;  

@property (assign,nonatomic) sqlite3 *db;  

@property (weak, nonatomic) IBOutlet UITableView *tableVIew;  

@property (strong,nonatomic) NSMutableArray *shops;  

- (IBAction)insertShop;  

  

@end  

  

@implementation ViewController  

  

- (void)viewDidLoad {  

    [super viewDidLoad];  

     

    //初始化数据库  

    [self setupDB];  

      

    [self setupData];  

      

    // 增加搜索框  

    UISearchBar *searchBar = [[UISearchBar alloc] init];  

    searchBar.frame = CGRectMake(0, 0, 320, 44);  

    searchBar.delegate = self;  

    self.tableVIew.tableHeaderView = searchBar;  

}  

  

- (void)didReceiveMemoryWarning {  

    [super didReceiveMemoryWarning];  

    // Dispose of any resources that can be recreated.  

}  

  

-(NSMutableArray *)shops{  

    if (!_shops) {  

        _shops = [[NSMutableArray alloc] init];  

    }  

    return _shops;  

}  

  

//初始化数据库  

-(void)setupDB{  

    //沙盒路径  

    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"shops.sqlite"];  

    NSLog(@"%@",filename);  

    // 如果数据库文件不存在, 系统会自动创建文件自动初始化数据  

    // sqlite3_open([path UTF8String], &db);  参入:一:存放地址  二:数据库实例  

    int status = sqlite3_open(filename.UTF8String, &_db); //返回SQLITE_OK代码打开成功  

    if (status == SQLITE_OK) {//打开成功  

        //创建表  

        const char  *sql= "create table if not exists t_shop(id integer primary key,name text not null,price real)";  

        charchar *errmsg = NULL;  

        sqlite3_exec(self.db, sql, NULL, NULL, &errmsg);  

          

        if (errmsg) {  

            NSLog(@"创建表失败!%s",errmsg);  

        }  

    }else{  

        NSLog(@"打开数据库失败!");  

    }  

}  

  

//新增商品  

- (IBAction)insertShop {  

    NSString *sql = [NSString stringWithFormat:@"insert into t_shop(name,price) values('%@',%f)",self.nameField.text,self.priceFIeld.text.doubleValue];  

    charchar *errmsg = NULL;  

    sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, &errmsg);  

    if (errmsg) {  

        NSLog(@"添加商品失败!");  

    }else{  

        [self alert];  

        ZXHShop *shop = [[ZXHShop alloc] init];  

        shop.name = self.nameField.text;  

        shop.price = self.priceFIeld.text;  

        [self.shops addObject:shop];  

       self.nameField.text = @"";  

       self.priceFIeld.text = @"";  

         

        [self.tableVIew reloadData];  

  

    }  

}  

/** 

 查询数据 

 */  

-(void)setupData{  

    const charchar *sql = "select name,price from t_shop";  

    sqlite3_stmt *stmt = NULL;  

    int status = sqlite3_prepare_v2(self.db, sql , -1, &stmt, NULL);  

    if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确  

        while (sqlite3_step(stmt) == SQLITE_ROW) {// 成功取出一条数据  

           const  charchar *name = (const  charchar *)sqlite3_column_text(stmt, 0);  

           const  charchar *price = (const  charchar *)sqlite3_column_text(stmt, 1);  

            ZXHShop *shop = [[ZXHShop alloc] init];  

            shop.name = [NSString stringWithUTF8String:name];  

            shop.price = [NSString stringWithUTF8String:price];  

            [self.shops addObject:shop];  

        }  

          

    }  

}  

  

-(void)alert{  

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NULL message:@"新增成功" preferredStyle:UIAlertControllerStyleAlert];  

      

    UIAlertAction *close = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil];  

      

    [alert addAction:close];  

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

}  

  

#pragma mark table数据源方法  

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{  

    return self.shops.count;  

}  

  

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{  

    static  NSString *ID = @"shop";  

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];  

    if (!cell) {  

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];  

        cell.backgroundColor = [UIColor grayColor];  

    }  

    ZXHShop *shop = self.shops[indexPath.row];  

    cell.textLabel.text = shop.name;  

    cell.detailTextLabel.text = shop.price;  

    cell.detailTextLabel.textColor = [UIColor redColor];  

      

    return cell;  

}  

  

#pragma mark searchBarDelegate   

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{  

    [self.shops removeAllObjects];  
d5b4

    NSString *sql = [NSString stringWithFormat:@"select name,price from t_shop where name like '%%%@%%' or price like '%%%@%%'",searchText,searchText];  

    sqlite3_stmt *stmt = NULL;  

    int status = sqlite3_prepare_v2(self.db, sql.UTF8String, -1, &stmt, NULL);  

    if (status == SQLITE_OK) {  

        while (sqlite3_step(stmt) == SQLITE_ROW) {  

            const charchar *name = (const charchar *)sqlite3_column_text(stmt, 0);  

            const charchar *price = (const charchar *)sqlite3_column_text(stmt, 1);  

              

            ZXHShop *shop = [[ZXHShop alloc]init];  

            shop.name = [NSString stringWithUTF8String:name];  

            shop.price = [NSString stringWithUTF8String:price];  

            [self.shops addObject:shop];  

        }  

    }  

    [self.tableVIew reloadData];  

      

      

}  

  

@end 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: