您的位置:首页 > 数据库

数据库01-sqlite3 (了解)

2015-06-12 17:01 218 查看
iOS中的数据存储方式:

Plist(NSArray\NSDictionary)

Preference(偏好设置\NSUserDefaults)

NSCoding(NSKeyedArchiver\NSkeyedUnarchiver)

SQLite3 (本次介绍)

Core Data

SQLite将数据划分为以下几种存储类型:

integer : 整型值

real : 浮点值

text : 文本字符串

blob : 二进制数据(比如文件)

实际上SQLite是无类型的

就算声明为integer类型,还是能存储字符串文本(主键除外)

建表时声明啥类型或者不声明类型都可以,也就意味着创表语句可以这么写:

create table t_student(name, age);

为了保持良好的编程规范、方便程序员之间的交流,编写建表语句的时候最好加上每个字段的具体类型

sqlite3 (原生态 有c语言 没有封装)

1.打开数据库
int sqlite3_open(
const char *filename,   // 数据库的文件路径
sqlite3 **ppDb          // 数据库实例
);

2.执行任何SQL语句
int sqlite3_exec(
sqlite3*,                                  // 一个打开的数据库实例
const char *sql,                           // 需要执行的SQL语句
int (*callback)(void*,int,char**,char**),  // SQL语句执行完毕后的回调
void *,                                    // 回调函数的第1个参数
char **errmsg                              // 错误信息
);

3.检查SQL语句的合法性(查询前的准备)
int sqlite3_prepare_v2(
sqlite3 *db,            // 数据库实例
const char *zSql,       // 需要检查的SQL语句
int nByte,              // SQL语句的最大字节长度
sqlite3_stmt **ppStmt,  // sqlite3_stmt实例,用来获得数据库数据
const char **pzTail
);

4.查询一行数据
int sqlite3_step(sqlite3_stmt*); // 如果查询到一行数据,就会返回SQLITE_ROW

5.利用stmt获得某一字段的值(字段的下标从0开始)
double sqlite3_column_double(sqlite3_stmt*, int iCol);  // 浮点数据
int sqlite3_column_int(sqlite3_stmt*, int iCol); // 整型数据
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); // 长整型数据
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); // 二进制文本数据
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);  // 字符串数据


sqlite3 (经过模型封装)

//
//  HMViewController.m
//  01-SQL的基本使用(了解)
//
//  Created by apple on 14/11/16.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HMViewController.h"
#import <sqlite3.h>
#import "HMShop.h"

@interface HMViewController () <UITableViewDataSource, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *priceField;
/** 数据库对象实例 */
@property (nonatomic, assign) sqlite3 *db;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)insert;
@property (nonatomic, strong) NSMutableArray *shops;
@end

@implementation HMViewController

- (NSMutableArray *)shops
{
if (!_shops) {
self.shops = [[NSMutableArray alloc] init];
}
return _shops;
}

- (void)viewDidLoad
{
[super viewDidLoad];

// 增加搜索框
UISearchBar *searchBar = [[UISearchBar alloc] init];
searchBar.frame = CGRectMake(0, 0, 320, 44);
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;

// 初始化数据库
[self setupDb];

// 查询数据
[self setupData];

// 关闭数据库
//    sqlite3_close();
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self.shops removeAllObjects];

NSString *sql = [NSString stringWithFormat:@"SELECT na
4000
me,price FROM t_shop WHERE name LIKE '%%%@%%' OR  price LIKE '%%%@%%' ;", searchText, searchText];
// stmt是用来取出查询结果的
sqlite3_stmt *stmt = NULL;
// 准备
int status = sqlite3_prepare_v2(self.db, sql.UTF8String, -1, &stmt, NULL);
if (status == SQLITE_OK) { // 准备成功 -- SQL语句正确
while (sqlite3_step(stmt) == SQLITE_ROW) { // 成功取出一条数据
const char *name = (const char *)sqlite3_column_text(stmt, 0);
const char *price = (const char *)sqlite3_column_text(stmt, 1);

HMShop *shop = [[HMShop alloc] init];
shop.name = [NSString stringWithUTF8String:name];
shop.price = [NSString stringWithUTF8String:price];
[self.shops addObject:shop];
}
}

[self.tableView reloadData];
}

/**
查询数据
*/
- (void)setupData
{
const char *sql = "SELECT name,price FROM t_shop;";
// stmt是用来取出查询结果的
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 char *name = (const char *)sqlite3_column_text(stmt, 0);
const char *price = (const char *)sqlite3_column_text(stmt, 1);

HMShop *shop = [[HMShop alloc] init];
shop.name = [NSString stringWithUTF8String:name];
shop.price = [NSString stringWithUTF8String:price];
[self.shops addObject:shop];
}
}
}

/**
初始化数据库
*/
- (void)setupDb
{
// 打开数据库(连接数据库)
NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
// 如果数据库文件不存在, 系统会自动创建文件自动初始化数据库
int status = sqlite3_open(filename.UTF8String, &_db);
if (status == SQLITE_OK) { // 打开成功
NSLog(@"打开数据库成功");

// 创表
const char *sql = "CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, name text NOT NULL, price real);";
char *errmsg = NULL;
sqlite3_exec(self.db, sql, NULL, NULL, &errmsg);
if (errmsg) {
NSLog(@"创表失败--%s", errmsg);
}
} else { // 打开失败
NSLog(@"打开数据库失败");
}
}

- (IBAction)insert {
NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_shop(name, price) VALUES ('%@', %f);", self.nameField.text, self.priceField.text.doubleValue];
sqlite3_exec(self.db, sql.UTF8String, NULL, NULL, NULL);

// 刷新表格
HMShop *shop = [[HMShop alloc] init];
shop.name = self.nameField.text;
shop.price = self.priceField.text;
[self.shops addObject:shop];
[self.tableView reloadData];
}

#pragma mark - 数据源方法
- (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];
}

HMShop *shop = self.shops[indexPath.row];
cell.textLabel.text = shop.name;
cell.detailTextLabel.text = shop.price;

return cell;
}
@end

/**
NSMutableString *sql = [NSMutableString string];

for (int i = 0; i<1000; i++) {
NSString *name = [NSString stringWithFormat:@"iPhone%d", i];
double price = arc4random() % 10000 + 100;
int leftCount = arc4random() % 1000;
[sql appendFormat:@"insert into t_shop(name, price, left_count) values ('%@', %f, %d);\n", name, price, leftCount];
}

[sql writeToFile:@"/Users/apple/Desktop/shops.sql" atomically:YES encoding:NSUTF8StringEncoding error:nil];
*/


模型代码

#import <Foundation/Foundation.h>

@interface HMShop : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *price;
@end

实现文件没有东西的···
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据 ios