GVKun编程网logo

sqlite3_iphone

15

如果您想了解sqlite3_iphone的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析iOSSQLite3sqlite3_column_text、ios–ObjectiveC–sqlite3

如果您想了解sqlite3_iphone的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析iOS SQLite3 sqlite3_column_text、ios – Objective C – sqlite3_open即使应用了sqlite3_close(),内存也会泄漏、ios – 如何调用sqlite3_errmsg来了解sqlite3_prepare_v2失败的原因、iphone – Sqlite3 DB下载路径的各个方面,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

sqlite3_iphone

sqlite3_iphone

1. 预备知识

读者需要有一定的sqlite数据库知识,懂得基本的sql语句,掌握OSX系统terminal终端 以及 XCode编译器 的基本操作。

2. 创建数据库

打开 Applications-Utilities-Terminal,可见终端窗口。

假设当前系统用户为Smitty,可在终端窗口内键入如下命令:

cd /Users/Smitty/Documents

mkdir sqliteDemo

cd sqliteDemo

sqlite3 PersonDatabase.sql

至此,你已经在/Users/lookaflyingdonkey/Documents目录下创建了一个新的目录sqliteDemo,并使用 sqlite3命令开启了sqlite终端,准备建立数据库结构并输入数据。

举例来说,若我们要建立的数据库表person需要有如下结构:唯一的id值,名字,职位描述,头像图片地址,那么下列命令将创建这个表,并添加几个人的纪录。

CREATE TABLE person (id INTEGER PRIMARY KEY,name VARCHAR(50),title TEXT,icon VARCHAR(255) );

INSERT INTO person (name,title,icon) VALUES('Peter','handy man','http://dblog.com.au/wp-content/elephant.jpg');

INSERT INTO person (name,icon) VALUES('Susan','manager','http://dblog.com.au/wp-content/monkey.jpg');

INSERT INTO person (name,icon) VALUES('Wilson','developer','http://dblog.com.au/wp-content/kangaroo.jpg');

执行完这几步后,可运行命令"SELECT * FROM person;",检查数据库中是否已存在上面插入的数据。一旦确认一切正常,可用命令".quit"退出sqlite 命令行模式。

3. 创建项目

现在让我门创建Xcode项目。

首先在Xcode中选择创建一个新的” Navigation-Based Application“

输入项目名称"sqliteDemo",由于之前在同一位置创建了同名目录,Xcode将会询问是否覆盖已经存在的目录sqliteDemo,选则是。这将使项目目录结构如下图所示。

4. 将sqlite框架和PersonDatabas数据库导入项目

首先我们需要将sqlite库引入项目。请右键点击左部菜单中的"Frameworks"目录,选择“Add > Existing Frameworks…”,

然后在本地目录中选择“/Developer/Platforms/iPhoneOS.platform/Developer /SDKs/iPhoneOS3.0.sdk/usr/lib/”,找到“libsqlite3.0.dylib”文件并双击。

一个弹出窗口将出现,点击其中“Add”按钮将库添加入项目中。

我们也需要将PersonDatabas 数据库导入Resources目录。请右键点击“Resources”目录,选择“Add > Existing Files…”,在本地目录中选择“/Users/Smitty/Documents/sqliteDemo/”,双击PersonDatabase.sql文件,点击弹出窗口中的“Add”按钮将其导入当前项目。

5. 开始编程

首先创建一个Person类。右键点击“Classes”目录,选择“Add > New File…”,在弹出窗口中选择“iPhone OS > Cocoa Touch Class > Objective-C class > NSObject” 并点击“Next”按钮。在下一窗口中,设置File Name为“Person.m”。点击“Finish”按钮完成创建。

修改Classes/Person.h为:

@interface Person : NSObject {

Nsstring *name;

Nsstring *title;

Nsstring *iconURL;

}

@property (nonatomic,retain) Nsstring *name;

@property (nonatomic,retain) Nsstring *title;

@property (nonatomic,retain) Nsstring *iconURL;

-(id)initWithName:(Nsstring *)n title:(Nsstring *)t url:(Nsstring *)u;

@end

修改Classes/Person.m为:

#import "Person.h"

@implementation Person

@synthesize name,iconURL;

-(id)initWithName:(Nsstring *)n title:(Nsstring *)t url:(Nsstring *)u {

self.name=n;

self.title=t;

self.iconURL=u;

return self;

}

@end

修改Other Sources/main.m为:

#import

#import "Person.h"

int main(int argc,char *argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//setup database name.

Nsstring *databaseName = @"PersonDatabase.sql";

// Get the path to the documents directory and append the databaseName

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

Nsstring *documentsDir = [documentPaths objectAtIndex:0];

Nsstring *databasePath = [documentsDirstringByAppendingPathComponent:databaseName];

// Create a FileManager object,we will use this to check the status

// of the database and to copy it over if required

NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem

BOOL success = [fileManager fileExistsAtPath:databasePath];

// If the database already exists then return without doing anything

if(!success){

// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package

Nsstring *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// copy the database from the package to the users filesystem

[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

}

// Query the database for all person records and construct the "person" array

sqlite3 *database;

// Init the animals Array

NSMutableArray *personArr = [[NSMutableArray alloc] init];

// Open the database from the users filessytem

if(sqlite3_open([databasePath UTF8String],&database) == sqlITE_OK) {

// Setup the sql Statement and compile it for faster access

const char *sqlStatement = "select * from person";

sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database,sqlStatement,-1,&compiledStatement,NULL) == sqlITE_OK) {

// Loop through the results and add them to the Feeds array

while(sqlite3_step(compiledStatement) == sqlITE_ROW) {

// Read the data from the result row

Nsstring *aName = [Nsstring stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,1)];

Nsstring *aTitle = [Nsstring stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,2)];

Nsstring *aIconUrl = [Nsstring stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,3)];

// Create a new animal object with the data from the database

Person *person = [[Person alloc] initWithName:aName title:aTitle url:aIconUrl];

// Add the animal object to the animals Array

[personArr addobject:person];

[person release];

}

}

// Release the compiled statement from memory

sqlite3_finalize(compiledStatement);

}

sqlite3_close(database);

for (Person *tmpPerson in personArr) {

NSLog(@"You can see %@ %@'s icon at %@",tmpPerson.title,tmpPerson.name,tmpPerson.iconURL);

[tmpPerson release];

}

NSLog(@"Done.");

[personArr release];

[fileManager release];

[pool release];

return (0);

}

6. 编译执行

完成修改后,运行“Build > Build and Run”,关掉弹出的iPhone Simulator窗口,选择"Run > Console" 打开控制台,可看到如下输出信息。

参考:

http://www.cnblogs.com/AlexLiu/archive/2010/04/21/1716740.html

iOS SQLite3 sqlite3_column_text

iOS SQLite3 sqlite3_column_text


const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);


    其中参数 iCol 为列的序号,从 0 开始。如果返回值有多行,则可以再次调用 sqlite3_step 函数,然后由 sqlite3_column_* 函数取得返回值。


例如:

"SELECT ID, KEEP1 FROM COLLECTION ORDER BY ID"

返回的值有 ID, KEEP1

使用 sqlite3_column_text (sqlite3_stmt*, int iCol); 的时候,iCol = 0 是返回 ID,iCol =1 是返回 KEEP1.

ios – Objective C – sqlite3_open即使应用了sqlite3_close(),内存也会泄漏

ios – Objective C – sqlite3_open即使应用了sqlite3_close(),内存也会泄漏

即使应用sqlite_close,sqlite3_finalize,我也会在sqlite3_open中出现内存泄漏,请指导我出错的地方.项目在非ARC.

-(BOOL)saveMedia:(NSDictionary *)details Download:(NSInteger)completed
{
    //NSLog(@"media savemedia %@",[details objectForKey:@"type"]);
    BOOL saved = FALSE;
    NSInteger exists = [self findMedia:[details objectForKey:@"media_id"] playlist_id:[details objectForKey:@"playlist_id"] type:[details objectForKey:@"type"]];
    sqlite3_stmt    *statement;

    self.databasePath = [self getDBPath];
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath,&wazzupco) == sqlITE_OK)
    {
        const char *query_stmt;
        if (exists == 0)
        {
            query_stmt = "INSERT INTO media (media_id,title,description,file,views,thumbnail,version,playlist,playlist_id,author,created_at,type,playlist_created,timeout,playlist_order,media_order,playlist_promo_text,playlist_promo_url,playlist_promo_img,video_promo_text,video_promo_url,video_promo_img,dev_id,device_id,downloaded,slide_timeout) VALUES (?,?,?)";
        }
        else if([[details objectForKey:@"version"] integerValue] > exists)
        {
            Nsstring *querysql = [Nsstring stringWithFormat:@"UPDATE %@ SET media_id=?,title=?,description=?,file=?,views=?,thumbnail=?,version=?,playlist=?,playlist_id=?,author=?,created_at=?,type=?,playlist_created=?,timeout=?,playlist_order=?,media_order=?,playlist_promo_text=?,playlist_promo_url=?,playlist_promo_img=?,video_promo_text=?,video_promo_url=?,video_promo_img=?,dev_id=?,device_id=?,downloaded=?,slide_timeout=? WHERE media_id='%@' AND playlist_id='%@' AND type='%@'",TABLE_MEDIA,[details objectForKey:@"media_id"],[details objectForKey:@"playlist_id"],[details objectForKey:@"type"]];
            query_stmt = [querysql UTF8String];
        }
        else
        {
            //to make sure we won't update the database entry unless its a newer version
            return FALSE;
        }
        sqlite3_prepare_v2(wazzupco,query_stmt,-1,&statement,NULL);

        sqlite3_bind_text(statement,1,[[details objectForKey:@"media_id"] UTF8String],NULL);
        sqlite3_bind_text(statement,2,[[details objectForKey:@"title"] UTF8String],3,[[details objectForKey:@"description"] UTF8String],4,[[details objectForKey:@"file"] UTF8String],5,[[details objectForKey:@"views"] UTF8String],6,[[details objectForKey:@"thumbnail"] UTF8String],7,[[details objectForKey:@"version"] UTF8String],8,[[details objectForKey:@"playlist"] UTF8String],9,[[details objectForKey:@"playlist_id"] UTF8String],10,[[details objectForKey:@"author"] UTF8String],11,[[details objectForKey:@"created_at"] UTF8String],12,[[details objectForKey:@"type"] UTF8String],13,[[details objectForKey:@"playlist_created"] UTF8String],14,[[details objectForKey:@"timeout"] UTF8String],NULL);
        sqlite3_bind_int(statement,15,[[details objectForKey:@"playlist_order"] intValue]);
        sqlite3_bind_int(statement,16,[[details objectForKey:@"media_order"] intValue]);
        sqlite3_bind_text(statement,17,[[details objectForKey:@"playlist_promo_text"] UTF8String],18,[[details objectForKey:@"playlist_promo_url"] UTF8String],19,[[details objectForKey:@"playlist_promo_img"] UTF8String],20,[[details objectForKey:@"video_promo_text"] UTF8String],21,[[details objectForKey:@"video_promo_url"] UTF8String],22,[[details objectForKey:@"video_promo_img"] UTF8String],23,[[details objectForKey:@"dev_id"] intValue]);
        sqlite3_bind_text(statement,24,[[details objectForKey:@"device_id"] UTF8String],25,(int)completed);
        sqlite3_bind_text(statement,26,[[details objectForKey:@"slide_timeout"] UTF8String],NULL);        
        if (sqlite3_step(statement) == sqlITE_DONE)
        {
            NSLog(@"media added. type:%@",[details objectForKey:@"type"]);
            saved = TRUE;
        }
        sqlite3_finalize(statement);
        //sqlite3_free(statement);
        //sqlite3_reset(statement);
    }
    sqlite3_close(wazzupco);
    if (completed != 0 && saved)
    {
        [self updateMediaStatus:[details objectForKey:@"file"] Download:1];
    }

    return saved;
}

在上面的代码中,我通过考虑数据是否已经存在,将数据从NSdictionary插入或更新到sqlite表.该方法执行正常,但它会产生严重的内存泄漏(该方法从循环中多次调用),当在Instrument中检查时,它显示泄漏位于if(sqlite3_open(dbpath,& wazzupco)== sqlITE_OK).

来自仪器

泄露的对象:Malloc 64Bytes

18

地址
大小:1.12KB
责任图书馆:libsqlite3.dylib
负责框架:0x34bdce30

解决方法

当执行“else”情况时,似乎上述代码中的内存泄漏.

if (sqlite3_open(dbpath,&wazzupco) == sqlITE_OK)
{
    const char *query_stmt;
    if (exists == 0)
    {
        query_stmt = "INSERT INTO media (media_id,?)";
    }
    else if([[details objectForKey:@"version"] integerValue] > exists)
    {
        Nsstring *querysql = [Nsstring stringWithFormat:@"UPDATE %@ SET media_id=?,[details objectForKey:@"type"]];
        query_stmt = [querysql UTF8String];
    }
    else
    {
        //to make sure we won't update the database entry unless its a newer version
        return FALSE;
    }

触发else情况时,未到达sqlite3_close()并导致sqlite3_open发生内存泄漏

ios – 如何调用sqlite3_errmsg来了解sqlite3_prepare_v2失败的原因

ios – 如何调用sqlite3_errmsg来了解sqlite3_prepare_v2失败的原因

基于C的函数sqlite3_prepare_v2返回1.我只想知道可读形式的错误消息并更正我的代码.我正在学习这个作为raywinderlich博客的教程.我遇到过sqlite3_errmsg,我不知道如何使用sqlite3_errmsg函数.

虽然here问了同样的问题,但遗憾的是仍然没有答案.

我想知道错误和纠正将非常感激.谢谢.

- (NSArray *)FailedBankInfos {
    NSMutableArray *retval = [[NSMutableArray alloc]init];
    Nsstring *query = @"SELECT id,name,city,state FROM Failed_banks ORDER BY close_date DESC";
    sqlite3_stmt *statement;
    int tmp  = sqlite3_prepare_v2(_database,[query UTF8String],-1,&statement,nil);
    NSLog(@"%i",tmp); // printing 1
    if (sqlite3_prepare_v2(_database,nil)
        == sqlITE_OK) {
        while (sqlite3_step(statement) == sqlITE_ROW) {
            int uniqueId = sqlite3_column_int(statement,0);
            char *nameChars = (char *) sqlite3_column_text(statement,1);
            char *cityChars = (char *) sqlite3_column_text(statement,2);
            char *stateChars = (char *) sqlite3_column_text(statement,3);

            Nsstring *name = [[Nsstring alloc] initWithUTF8String:nameChars];
            Nsstring *city = [[Nsstring alloc] initWithUTF8String:cityChars];
            Nsstring *state = [[Nsstring alloc] initWithUTF8String:stateChars];
            NSLog(@"name is  : %@",name);
             NSLog(@"city is : %@",city);
            FailedBankInfo *info = [[FailedBankInfo alloc]
                                    initWithUniqueId:uniqueId name:name city:city state:state];
            [retval addobject:info];
        }
        sqlite3_finalize(statement);
    }
    else
    {
        // if part is failing and control is arriving in else.
    }
    return retval;

}

解决方法

您可以使用sqlite3_errmsg(),如:

NSLog(@"Database Error Message : %s",sqlite3_errmsg(_database));

您也可以使用sqlite3_errstr().

The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
text that describes the error,as either UTF-8 or UTF-16 respectively.
Memory to hold the error message string is managed internally. The
application does not need to worry about freeing the result. However,
the error string might be overwritten or deallocated by subsequent
calls to other sqlite interface functions.

The sqlite3_errstr() interface returns the English-language text that
describes the result code,as UTF-8. Memory to hold the error message
string is managed internally and must not be freed by the application.

参考SQLite Error Messages

iphone – Sqlite3 DB下载路径

iphone – Sqlite3 DB下载路径

有谁知道从哪个链接我可以下载sqlite3数据库的 Xcode.我想在我的 Xcode4.2项目中使用Database.请提供下载链接.

解决方法

它不像下载数据库.有一些选项你必须通过终端或Mozilla firefox在你的项目中创建sqlite3数据库(为sqlite3管理器提供附加组件 – 谷歌它).创建数据库后,您必须在Apple开发人员文档提供的项目中添加libsqlite3.0.dylib Framework.

有关详细信息,请参阅This教程.哪个是开始使用sqlite3的好开始.

关于sqlite3_iphone的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于iOS SQLite3 sqlite3_column_text、ios – Objective C – sqlite3_open即使应用了sqlite3_close(),内存也会泄漏、ios – 如何调用sqlite3_errmsg来了解sqlite3_prepare_v2失败的原因、iphone – Sqlite3 DB下载路径等相关知识的信息别忘了在本站进行查找喔。

本文标签: