因为我主要负责咱们小组项目数据库模块的部分因此这几天都一直在研究在iphone中最为经常使用的一个简单数据库sqlite,本身也搜集不少资料,所以在这里总结一下这几天的学习成果:
- 1.Sqlite操做简明教程:http://hlee.javaeye.com/blog/359962
- 2.iphone访问本地数据库sqlite3:http://blog.csdn.net/LuWei103/archive/2009/08/08/4425045.aspx
- 3.iphone开发-SQLite数据库使用:http://yuxiang13115204.blog.163.com/blog/static/26802022200921410845642/
感谢以上文章做者能让我这个初学者可以快速的学习关于iphone开发中sqlite的使用,详细文章:
sqlite操做简明教程
SQLite顾名思议是以 SQL为基础的数据库软件,SQL是一套强大的数据库语言,主要概念是由「数据库」、「资料表」(table)、「查询指令」(queries)等单元组 成的「关联性数据库」(进一步的概念可参考网络上各类关于SQL及关联性数据库的文件)。由于SQL的查询功能强大,语法一致而入门容易,所以成为现今主 流数据库的标准语言(微软、Oracle等大厂的数据库软件都提供SQL语法的查询及操做)。
如下咱们就创建数据库、创建资料表及索引、新增资料、查询资料、更改资料、移除资料、sqlite3命令列选项等几个项目作简单的介绍。
目录
- 1 创建数据库档案
- 2 在sqlite3提示列下操做
- 3 SQL的指令格式
- 4 创建资料表
- 5 创建索引
- 6 加入一笔资料
- 7 查询资料
- 8 如何更改或删除资料
- 9 其余sqlite的特别用法
- 10 小结
列表
创建数据库档案
用sqlite3创建数据库的方法很简单,只要在shell下键入(如下$符号为shell提示号,请勿键入):
若是目录下没有foo.db,sqlite3就会创建这个数据库。sqlite3并无强制数据库档名要怎么取,所以若是你喜欢,也能够取个例如foo.icannameitwhateverilike的档名。
在sqlite3提示列下操做
进入了sqlite3以后,会看到如下文字:
SQLite version 3.1.3Enter ".help" for instructionssqlite>
这时若是使用.help能够取得求助,.quit则是离开(请注意:不是quit)
SQL的指令格式
因此的SQL指令都是以分号(;)结尾的。若是遇到两个减号(--)则表明注解,sqlite3会略过去。
创建资料表
假设咱们要建一个名叫film的资料表,只要键入如下指令就能够了:
- create table film(title, length, year, starring);
这样咱们就创建了一个名叫film的资料表,里面有name、length、year、starring四个字段。
这个create table指令的语法为:
- create table table_name(field1, field2, field3, ...);
table_name是资料表的名称,fieldx则是字段的名字。sqlite3与许多SQL数据库软件不一样的是,它不在意字段属于哪种资料型态:sqlite3的字段能够储存任何东西:文字、数字、大量文字(blub),它会在适时自动转换。
创建索引
若是资料表有至关多的资料,咱们便会创建索引来加快速度。比如说:
- create index film_title_index on film(title);
意思是针对film资料表的name字段,创建一个名叫film_name_index的索引。这个指令的语法为
- create index index_name on table_name(field_to_be_indexed);
一旦创建了索引,sqlite3会在针对该字段做查询时,自动使用该索引。这一切的操做都是在幕后自动发生的,无须使用者特别指令。
加入一笔资料
接下来咱们要加入资料了,加入的方法为使用insert into指令,语法为:
- insert into table_name values(data1, data2, data3, ...);
例如咱们能够加入
- insert into film values ('Silence of the Lambs, The', 118, 1991, 'Jodie Foster');insert into film values ('Contact', 153, 1997, 'Jodie Foster');insert into film values ('Crouching Tiger, Hidden Dragon', 120, 2000, 'Yun-Fat Chow');insert into film values ('Hours, The', 114, 2002, 'Nicole Kidman');
若是该字段没有资料,咱们能够填NULL。
查询资料
讲到这里,咱们终于要开始介绍SQL最强大的select指令了。咱们首先简单介绍select的基本句型:
- select columns from table_name where expression;
最多见的用法,固然是倒出全部数据库的内容:
若是资料太多了,咱们或许会想限制笔数:
- select * from film limit 10;
或是照着电影年份来排列:
- select * from film order by year limit 10;
或是年份比较近的电影先列出来:
- select * from film order by year desc limit 10;
或是咱们只想看电影名称跟年份:
- select title, year from film order by year desc limit 10;
查全部茱蒂佛斯特演过的电影:
- select * from film where starring='Jodie Foster';
查全部演员名字开头叫茱蒂的电影('%' 符号即是 SQL 的万用字符):
- select * from film where starring like 'Jodie%';
查全部演员名字以茱蒂开头、年份晚于1985年、年份晚的优先列出、最多十笔,只列出电影名称和年份:
- select title, year from film where starring like 'Jodie%' and year >= 1985 order by year desc limit 10;
有时候咱们只想知道数据库一共有多少笔资料:
- select count(*) from film;
有时候咱们只想知道1985年之后的电影有几部:
- select count(*) from film where year >= 1985;
(进一步的各类组合,要去看SQL专书,不过你大概已经知道SQL为何这么流行了:这种语言容许你将各类查询条件组合在一块儿──而咱们还没提到「跨数据库的联合查询」呢!)
如何更改或删除资料
了解select的用法很是重要,由于要在sqlite更改或删除一笔资料,也是靠一样的语法。
例若有一笔资料的名字打错了:
- update film set starring='Jodie Foster' where starring='Jodee Foster';
就会把主角字段里,被打成'Jodee Foster'的那笔(或多笔)资料,改回成Jodie Foster。
- delete from film where year < 1970;
就会删除全部年代早于1970年(不含)的电影了。
其余sqlite的特别用法
sqlite能够在shell底下直接执行命令:
- sqlite3 film.db "select * from film;"
输出 HTML 表格:
- sqlite3 -html film.db "select * from film;"
将数据库「倒出来」:
- sqlite3 film.db ".dump" > output.sql
利用输出的资料,创建一个如出一辙的数据库(加上以上指令,就是标准的SQL数据库备份了):
- sqlite3 film.db < output.sql
在大量插入资料时,你可能会须要先打这个指令:
begin;
插入完资料后要记得打这个指令,资料才会写进数据库中:
commit;
小结
以上咱们介绍了SQLite这套数据库系统的用法。事实上OS X也有诸于SQLiteManagerX这类的图形接口程序,能够便利数据库的操做。不过万变不离其宗,了解SQL指令操做,SQLite与其各家变种就很容易上手了。
至于为何要写这篇教学呢?除了由于OS X Tiger大量使用SQLite以外(例如:Safari的RSS reader,就是把文章存在SQLite数据库里!你能够开开看~/Library/Syndication/Database3这个档案,看看里面有 什么料),OpenVanilla从0.7.2开始,也引进了以SQLite为基础的词汇管理工具,以及全字库的注音输入法。由于使用SQLite,这两 个模块无论数据库内有多少笔资料,均可以作到「瞬间启动」以及至关快速的查询回应。
将一套方便好用的数据库软件包进OS X中,固然也算是Apple至关至关聪明的选择。再勤劳一点的朋友也许已经开始想拿SQLite来记录各类东西(像咱们其中就有一人写了个程序,自动记录 电池状态,写进SQLite数据库中再作统计......)了。想像空间可说至关宽广。
目前支援SQLite的程序语言,你能想到的大概都有了。这套数据库2005年还赢得了美国O'Reilly Open Source Conference的最佳开放源代码软件奖,奖评是「有什么东西能让Perl, Python, PHP, Ruby语言团结一致地支援的?就是SQLite」。因而可知SQLite的地位了。而SQLite程序很是小,更是少数打 "gcc -o sqlite3 *",不需任何特殊设定就能跨平台编译的程序。小而省,小而美,SQLite连网站都很少赘言,直指SQL语法精要及API使用方法,原做者大概也能够算 是某种程序设计之道(Tao of Programming)里所说的至人了。
iphone开发-SQLite数据库使用
我如今要使用SQLite3.0建立一个数据库,而后在数据库中建立一个表格。
首先要引入SQLite3.0的lib库。而后包含头文件#import <sqlite3.h>
【1】
打开数据库,若是没有,那么建立一个
sqlite3* database_;
-(BOOL) open{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sql"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL find = [fileManager fileExistsAtPath:path];
//找到数据库文件mydb.sql
if (find) {
NSLog(@"Database file have already existed.");
if(sqlite3_open([path UTF8String], &database_) != SQLITE_OK) {
sqlite3_close(database_);
NSLog(@"Error: open database file.");
return NO;
}
return YES;
}
if(sqlite3_open([path UTF8String], &database_) == SQLITE_OK) {
bFirstCreate_ = YES;
[self
createChannelsTable:database_];//在后面实现函数
createChannelsTable
return YES;
} else {
sqlite3_close(database_);
NSLog(@"Error: open database file.");
return NO;
}
return NO;
}
【2】建立表格
//建立表格,假设有五个字段,(id,cid,title,imageData ,imageLen )
//说明一下,id为表格的主键,必须有。
//cid,和title都是字符串,imageData是二进制数据,imageLen 是该二进制数据的长度。
- (BOOL) createChannelsTable:(sqlite3*)db{
char *sql = "CREATE TABLE channels (id integer primary key, \
cid text, \
title text, \
imageData BLOB, \
imageLen integer)";
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, sql, -1, &statement, nil) != SQLITE_OK) {
NSLog(@"Error: failed to prepare statement:create channels table");
return NO;
}
int success = sqlite3_step(statement);
sqlite3_finalize(statement);
if ( success != SQLITE_DONE) {
NSLog(@"Error: failed to dehydrate:CREATE TABLE channels");
return NO;
}
NSLog(@"Create table 'channels' successed.");
return YES;
}
【3】
向表格中插入一条记录
假设channle是一个数据结构体,保存了一条记录的内容。
- (BOOL) insertOneChannel:(Channel*)channel{
NSData* ImageData = UIImagePNGRepresentation( channel.image_);
NSInteger Imagelen = [ImageData length];
sqlite3_stmt *statement;
static char *sql = "INSERT INTO channels (cid,title,imageData,imageLen)\
VALUES(?,?,?,?)";
//问号的个数要和(cid,title,imageData,imageLen)里面字段的个数匹配,表明未知的值,将在下面将值和字段关联。
int success = sqlite3_prepare_v2(database_, sql, -1, &statement, NULL);
if (success != SQLITE_OK) {
NSLog(@"Error: failed to insert:channels");
return NO;
}
//这里的数字1,2,3,4表明第几个问号
sqlite3_bind_text(statement, 1, [channel.id_ UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [channel.title_ UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 3, [ImageData bytes], Imagelen, SQLITE_TRANSIENT);
sqlite3_bind_int(statement, 4, Imagelen);
success = sqlite3_step(statement);
sqlite3_finalize(statement);
if (success == SQLITE_ERROR) {
NSLog(@"Error: failed to insert into the database with message.");
return NO;
}
NSLog(@"Insert One Channel#############:id =
%@",channel.id_);
return YES;
}
【4】数据库查询
这里获取表格中全部的记录,放到数组fChannels中。
- (void) getChannels:(NSMutableArray*)fChannels{
sqlite3_stmt *statement = nil;
char *sql = "SELECT * FROM channels";
if (sqlite3_prepare_v2(database_, sql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(@"Error: failed to prepare statement with message:get channels.");
}
//查询结果集中一条一条的遍历全部的记录,这里的数字对应的是列值。
while (sqlite3_step(statement) == SQLITE_ROW) {
char* cid = (char*)sqlite3_column_text(statement, 1);
char* title = (char*)sqlite3_column_text(statement, 2);
Byte* imageData = (Byte*)sqlite3_column_blob(statement, 3);
int imageLen = sqlite3_column_int(statement, 4);
Channel* channel = [[Channel alloc] init];
if(cid)
channel.id_ = [NSString stringWithUTF8String:cid];
if(title)
channel.title_ = [NSString stringWithUTF8String:title];
if(imageData){
UIImage* image = [UIImage imageWithData:[NSData dataWithBytes:imageData length:imageLen]];
channel.image_ = image;
}
[fChannels addObject:channel];
[channel release];
}
sqlite3_finalize(statement);
}
iphone访问本地数据库sqlite3
Phone也支持访问本地数据库Sqlite 3。这里简单的介绍一下iPhone上Sqlite 3的使用方法。
首先须要在项目中引用
Sqlite 3的开发包,下面是在iPhone SDK 3.0下的目录:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/lib/libsqlite3.0.dylib
到这里你须要事先用命令来建立
Sqlite 3的数据库文件,并在其中建立本身的表等等,而后做为资源文件添加到项目,而后在程序第一次运行的时候复制到程序下的Documents或其余目录下,关于
Sqlite 3的基本操做网上已经有很多文章,这里就不重复了。
在iPhone中使用
Sqlite 3主要步骤以下:
1 首先获取iPhone上
Sqlite 3的数据库文件的地址
2 打开
Sqlite 3的数据库文件
3 定义SQL文
4 邦定执行SQL所须要的参数
5 执行SQL文,并获取结果
6 释放资源
7 关闭
Sqlite 3数据库。
下面结合代码来示范一下。
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];
-
- sqlite3 *database;
- sqlite3_open([path UTF8String], &database);
-
- sqlite3_stmt *stmt;
- const char *sql = "SELECT * FROM table_name WHERE pk=? and name=?";
- sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);
-
- sqlite3_bind_int(stmt, 1, 1);
-
- sqlite3_bind_text(stmt, 2, [title UTF8String], -1, SQLITE_TRANSIENT);
-
- sqlite3_step(stmt);
-
- sqlite3_finalize(stmt);
-
- sqlite3_close(database);
这里只是粗略的给你们介绍了一下,更详细的资料请参考Apple的官方文档。