如何在iphone中连接sqlite?

如何在iphone中连接sqlite?,iphone,sqlite,Iphone,Sqlite,我正在用iphone开发一个应用程序,我是iphone新手。 请告诉我使用sqlite在iphone中打开/关闭/更新/删除数据库记录的代码 问候,, Vijaya阅读其网站上的sqlite文档。他们有API参考和教程。在XCode中,只需将libsqlite3.dylib添加到引用的框架中。import 在.h文件中 - (void)createEditableCopyOfDatabaseIfNeeded; + (sqlite3 *) getNewDBConnection; 在did

我正在用iphone开发一个应用程序,我是iphone新手。 请告诉我使用sqlite在iphone中打开/关闭/更新/删除数据库记录的代码

问候,,
Vijaya

阅读其网站上的sqlite文档。他们有API参考和教程。在XCode中,只需将libsqlite3.dylib添加到引用的框架中。

import 在.h文件中

- (void)createEditableCopyOfDatabaseIfNeeded;  
+ (sqlite3 *) getNewDBConnection;  
didfishLaunching
方法中的
appdelegate.m
中添加以下代码:

[self createEditableCopyOfDatabaseIfNeeded];

- (void)createEditableCopyOfDatabaseIfNeeded {  
    NSLog(@"Creating editable copy of database");  

    // First, test for existence.  

    BOOL success;  

    NSFileManager *fileManager = [NSFileManager defaultManager];  

    NSError *error;  

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);   
    NSString *documentsDirectory = [paths objectAtIndex:0];  

    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Scores.sqlite"];  

    success = [fileManager fileExistsAtPath:writableDBPath];  

    if (success) return;  

    // The writable database does not exist, so copy the default to the appropriate location.   
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Scores.sqlite"];  

    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];  

    if (!success) {  
        NSAssert1(0, @"Failed to create writable database file with message ‘%@’.", [error localizedDescription]);  
    }  
}

+ (sqlite3 *) getNewDBConnection {  
    sqlite3 *newDBconnection;  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsDirectory = [paths objectAtIndex:0];  
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Scores.sqlite"];  

    // Open the database. The database was prepared outside the application.  
    if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {  
        NSLog(@"Database Successfully Opened ");  
    } else {   
        NSLog(@"Error in opening database ");       
    }  

    return newDBconnection;  
}
在视图控制器中,调用插入等方法。在这里,我调用了从表中获取数据的方法

sqlite3* db =[iMemory_SharpenerAppDelegate getNewDBConnection];  
sqlite3_stmt *statement = nil;  
const char *sql = "select * from HighScore";  

if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK) {  
    NSAssert1(0,@"error prepearing statement",sqlite3_errmsg(db));  
} else {  
    while (sqlite3_step(statement)==SQLITE_ROW) {  
        //dt= [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];  
        dt = [NSString stringWithFormat:@"%s",(char *)sqlite3_column_text(statement, 0)];  
        //dt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];  
        NSLog(@"%@score==",dt);  
        [nmber addObject:dt];  
    }  

}  

sqlite3_finalize(statement);  
sqlite3_close(db);  
ViewController.h
#进口
#导入“sqlite3.h”
@界面视图控制器
{
IBUitextField*编号;
UITextField*名称,*地址;
IBUI按钮*保存、*更新、*删除、*清除、*查找、*显示数据;
sqlite3*contactDB;
IBUILabel*状态;
}
@属性(强,非原子)IBOutlet UITextField*编号;
@属性(强,非原子)IBOutlet UITextField*名称;
@属性(强,非原子)IBOutlet UITextField*地址;
@属性(保留,非原子)IBUILabel*状态;
-(iAction)保存数据:(id)发送方;
-(iAction)FindData:(id)发送方;
-(iAction)UpdateData:(id)发送方;
-(iAction)DeleteData:(id)发送方;
-(iAction)ClearData:(id)发送方;
-(iAction)ShowData:(id)发送方;
@结束
ViewController.m
#导入“ViewController.h”
#导入“ShowRecord.h”
@界面视图控制器()
{
NSString*docsDir;
NSArray*dirpath;
NSString*数据库路径;
}
@结束
@实现视图控制器
@综合姓名、地址、状态、编号;
-(无效)viewDidLoad
{
[自加载数据库];
[状态设置隐藏:真];
[超级视图下载];
//加载视图后,通常从nib执行任何其他设置。
}
-(无效)未收到记忆警告
{
[超级记忆警告];
//处置所有可以重新创建的资源。
}
-(无效)视图卸载{
self.name=nil;
self.address=nil;
self.status=nil;
}
-(void)LoadDB
{
//获取文档目录
dirpath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
docsDir=[dirpath objectAtIndex:0];
//生成数据库文件的路径
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@“student.db”];
NSFileManager*filemgr=[NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath]==否)
{
const char*dbpath=[databasePath UTF8String];
if(sqlite3\u打开(dbpath和contactDB)==SQLITE\u正常)
{
char*errMsg;
const char*sql_stmt=“创建表(如果不存在)(ID整型主键自动递增,名称文本,地址文本)”;
if(sqlite3执行(contactDB、sql stmt、NULL、NULL和errMsg)!=SQLITE\u确定)
{
status.text=@“未能创建表”;
}
其他的
{
status.text=@“成功创建表”;
}
sqlite3_关闭(contactDB);
}
其他的
{
status.text=@“无法打开/创建数据库”;
}
}
}
-(iAction)保存数据:(id)发件人
{
[状态设置隐藏:false];
sqlite3_stmt*语句;
const char*dbpath=[databasePath UTF8String];
if(sqlite3\u打开(dbpath和contactDB)==SQLITE\u正常)
{
NSString*insertSQL=[NSString stringWithFormat:@“插入螺柱(名称、地址)值(\“%@\”,\“%@\”),name.text,address.text];
常量字符*insert_stmt=[insertSQL UTF8String];
sqlite3\u prepare\u v2(contactDB,insert\u stmt,-1,&语句,NULL);
if(sqlite3\u步骤(语句)==SQLITE\u完成)
{
status.text=@“已添加联系人”;
name.text=@;
address.text=@;
}
其他的
{
status.text=@“添加联系人失败”;
}
sqlite3_最终确定(声明);
sqlite3_关闭(contactDB);
}
}
-(iAction)UpdateData:(id)发件人
{
[状态设置隐藏:false];
sqlite3_stmt*语句;
const char*dbpath=[databasePath UTF8String];
if(sqlite3\u打开(dbpath和contactDB)==SQLITE\u正常)
{
NSString*updateSQl=[NSString stringWithFormat:@“更新螺柱集名称=\“%@\”,地址=\“%@\”,其中id=\“%@\”,名称.文本,地址.文本,编号.文本];
const char*update_stmt=[updateSQl UTF8String];
sqlite3\u prepare\u v2(contactDB,update\u stmt,-1,&语句,NULL);
if(sqlite3\u步骤(语句)==SQLITE\u完成)
{
status.text=@“记录已更新”;
name.text=@;
地址.文本=@“;
否。文本=@;
}
其他的
{
status.text=@“记录未更新”;
}
}
}
-(iAction)DeleteData:(id)发件人
{
[状态设置隐藏:false];
sqlite3_stmt*语句;
const char*dbpath=[databasePath UTF8String];
if(sqlite3\u打开(dbpath和contactDB)==SQLITE\u正常){
NSString*deleteSql=[NSString stringWithFormat:@“从螺柱中删除,其中id=\“%@\”,no.text];
常量字符*delete_stmt=[deleteSql UTF8String];
sqlite3\u prepare\u v2(contactDB,delete\u stmt,-1,&语句,NULL);
if(sqlite3\u步骤(语句)==SQLITE\u完成)
{
status.text=@“记录已删除”;
name.text=@;
地址.文本=@“;
否。文本=@;
}
其他的
{
status.text=@“记录未删除”;
}
}
}
-(iAction)ClearData:(id)发送方
{
name.text=@;
否。文本=@;
地址.文本=@“;
}
-(iAction)ShowData:(id)发件人
{
ShowRecord*ShowRecord=[[ShowRecord alloc]initWithNibName:@“ShowRecord”bundle:nil];
[self.pushViewController:showrecord动画:是];
//ShowRecord*vc1=[[S
ViewController.h

#import <UIKit/UIKit.h>
#import "sqlite3.h"

@interface ViewController
{

     IBOutlet UITextField *no;
     UITextField *name,*address;

     IBOutlet UIButton *save,*update,*del,*clear,*Find,*showdata;

     sqlite3 *contactDB;

     IBOutlet UILabel *status;

}
@property (strong, nonatomic) IBOutlet UITextField *no;
@property (strong, nonatomic) IBOutlet UITextField *name;
@property (strong, nonatomic) IBOutlet UITextField *address;
@property (retain, nonatomic) IBOutlet UILabel *status;
- (IBAction)SaveData:(id)sender;
- (IBAction)FindData:(id)sender;
- (IBAction)UpdateData:(id)sender;
- (IBAction)DeleteData:(id)sender;
- (IBAction)ClearData:(id)sender;
- (IBAction)ShowData:(id)sender;

@end


ViewController.m


#import "ViewController.h"
#import "ShowRecord.h"
@interface ViewController ()
{
    NSString *docsDir;
    NSArray *dirPaths;
    NSString *databasePath;
}
@end

@implementation ViewController
@synthesize name, address,status,no;

- (void)viewDidLoad
{
    [self LoadDB];
    [status setHidden:TRUE];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
    self.name = nil;
    self.address = nil;

    self.status = nil;
}

-(void)LoadDB
{
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"student.db"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS stud (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                status.text = @"Failed to create table";
            }
            else
            {
                status.text = @"success Created table";
            }

            sqlite3_close(contactDB);

        }
        else
        {
            status.text = @"Failed to open/create database";
        }
    }
}
- (IBAction)SaveData:(id)sender
{
    [status setHidden:false];
    sqlite3_stmt    *statement;
    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat:                               @"INSERT INTO stud                             (name, address) VALUES (\"%@\", \"%@\")",                                                              name.text, address.text];
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(contactDB, insert_stmt,                                                                                 -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
           status.text = @"Contact added";
            name.text = @"";
            address.text = @"";
        }
        else
        {
            status.text = @"Failed to add contact";
        }
        sqlite3_finalize(statement);
        sqlite3_close(contactDB);

    }
}
- (IBAction)UpdateData:(id)sender
{
     [status setHidden:false];
    sqlite3_stmt *statement;
    const char *dbpath=[databasePath UTF8String];
    if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
    {
        NSString *updateSQl=[NSString stringWithFormat:@"update stud set name=\"%@\",address=\"%@\" where id=\"%@\" ",name.text,address.text,no.text];
        const char *update_stmt=[updateSQl UTF8String];
        sqlite3_prepare_v2(contactDB, update_stmt, -1, &statement, NULL);

        if (sqlite3_step(statement)==SQLITE_DONE)
        {
            status.text=@"Record Updated";
            name.text=@"";
            address.text=@"";
            no.text=@"";
        }
        else
        {
            status.text=@"Record Not Updated";
        }
    }
}
- (IBAction)DeleteData:(id)sender
{
     [status setHidden:false];
    sqlite3_stmt *statement;
    const char *dbpath=[databasePath UTF8String];
    if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) {
        NSString *deleteSql=[NSString stringWithFormat:@"delete from stud where id=\"%@\"",no.text];
        const char *delete_stmt=[deleteSql UTF8String];
        sqlite3_prepare_v2(contactDB, delete_stmt, -1, &statement, NULL);
        if(sqlite3_step(statement)==SQLITE_DONE)
        {
            status.text=@"Record Deleted";
            name.text=@"";
            address.text=@"";
            no.text=@"";

        }
        else
        {
            status.text=@"Record Not Deleted ";
        }

    }
}

- (IBAction)ClearData:(id)sender
{
    name.text=@"";
    no.text=@"";
    address.text=@"";
}

- (IBAction)ShowData:(id)sender
{
    ShowRecord *showrecord=[[ShowRecord alloc]initWithNibName:@"ShowRecord" bundle:nil];
    [self. pushViewController:showrecord animated:YES];

   // ShowRecord *vc1 = [[ShowRecord alloc]                                  initWithNibName:@"ViewControllerNext" bundle:nil];
    //[self.navigationController pushViewController:vc1 animated:YES];


}

- (IBAction)FindData:(id)sender
{
    [status setHidden:false];
    const char *dbpath = [databasePath UTF8String];
    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:
                              @"SELECT name,address FROM stud WHERE id=\"%@\"",
                              no.text];
        const char *query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(contactDB,
                               query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString  *namefield=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];

                NSString *addressField = [[NSString alloc]
                                          initWithUTF8String:
                                          (const char *) sqlite3_column_text(statement, 1)];
                name.text=namefield;
                address.text = addressField;
                status.text = @"Record Found";

            }
            else
            {
                status.text = @"Record Not Found";
                address.text = @"";
                name.text=@"";
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(contactDB);
    }
}

@end
#import "sqlLiteDemoViewController.h"
@interface sqlLiteDemoViewController (){
UILabel *lblName;
UILabel *lblRoll;
UILabel *lblAge;
UITextField *txtName;
UITextField *txtroll;
UISlider *sldAge;
}

@end

@implementation sqlLiteDemoViewController

- (void)viewDidLoad
{

NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:@"student.db"]];
NSLog(@"%@",_databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
    const char *dbpath = [_databasePath UTF8String];
    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt ="CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ROLL TEXT, AGE TEXT)";

        if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
        {
            NSLog(@"Failed to create table");
        }
        sqlite3_close(_contactDB);
        NSLog(@"Connection Successful");
    } else {
        NSLog(@"Failed to open/create database");
    }
}


UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapped)];

[self.view addGestureRecognizer:tapScroll];

[super viewDidLoad];
lblName = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 50)];
lblName.backgroundColor = [UIColor clearColor];
lblName.textColor=[UIColor blackColor];
lblName.text = @"Name";
[self.view addSubview:lblName];
lblRoll = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 100, 50)];
lblRoll.backgroundColor = [UIColor clearColor];
lblRoll.textColor=[UIColor blackColor];
lblRoll.text = @"Roll no";
[self.view addSubview:lblRoll];
lblAge = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, 100, 50)];
lblAge.backgroundColor = [UIColor clearColor];
lblAge.textColor=[UIColor blackColor];
lblAge.text = @"Age";
[self.view addSubview:lblAge];



txtName = [[UITextField alloc] initWithFrame:CGRectMake(80, 40, 200, 40)];
txtName.borderStyle = UITextBorderStyleRoundedRect;
txtName.font = [UIFont systemFontOfSize:15];
txtName.placeholder = @"Specify Name";
txtName.autocorrectionType = UITextAutocorrectionTypeNo;
txtName.keyboardType = UIKeyboardTypeDefault;
txtName.returnKeyType = UIReturnKeyDone;
txtName.clearButtonMode = UITextFieldViewModeWhileEditing;
txtName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtName.delegate = self;
[self.view addSubview:txtName];

txtroll = [[UITextField alloc] initWithFrame:CGRectMake(80, 90, 200, 40)];
txtroll.borderStyle = UITextBorderStyleRoundedRect;
txtroll.font = [UIFont systemFontOfSize:15];
txtroll.placeholder = @"Specify Roll";
txtroll.autocorrectionType = UITextAutocorrectionTypeNo;
txtroll.keyboardType = UIKeyboardTypeNumberPad;
txtroll.returnKeyType = UIReturnKeyDone;
txtroll.clearButtonMode = UITextFieldViewModeWhileEditing;
txtroll.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtroll.delegate = self;
[self.view addSubview:txtroll];


CGRect frame = CGRectMake(80.0, 140.0, 200.0, 40.0);
sldAge= [[UISlider alloc] initWithFrame:frame];
[sldAge setBackgroundColor:[UIColor clearColor]];
sldAge.minimumValue = 0;
sldAge.maximumValue = 30;
sldAge.continuous = YES;
sldAge.value = 15.0;
[self.view addSubview:sldAge];


UIButton *subButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
subButton.frame = CGRectMake(80.0, 200.0, 80.0, 30.0);
[subButton setTitle:@"Store" forState:UIControlStateNormal];
subButton.backgroundColor = [UIColor clearColor];
[subButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[subButton addTarget:self action:@selector(store:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:subButton];


UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame = CGRectMake(200.0, 200.0, 80.0, 30.0);
[srchButton setTitle:@"Search" forState:UIControlStateNormal];
srchButton.backgroundColor = [UIColor clearColor];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[srchButton addTarget:self action:@selector(find:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:srchButton];   
}

- (void)tapped {
[self.view endEditing:YES];
}
-(void)store:(id)sender{
@try{
NSLog(@"store called");
    sqlite3_stmt    *statement;
    const char *dbpath = (const char *)[_databasePath UTF8String];
    NSString *age=[NSString stringWithFormat:@"%g", sldAge.value];
    NSLog(@"Age is %@",age);
    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
    {

        NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO STUDENT (name, roll  , age) VALUES (\"%@\", \"%@\", \"%@\")",
                               txtName.text, txtroll.text, age];

        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(_contactDB, insert_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"Insertion Successful");
        } else {
            NSLog(@"Insertion Failure");
        }
        sqlite3_finalize(statement);
        sqlite3_close(_contactDB);
    }
}@catch (NSException *e) {
    NSLog(@"Exception : %s",sqlite3_errmsg(_contactDB));
}
}

- (void) find:(id)sender
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt    *statement;

if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat:@"SELECT roll, age FROM STUDENT WHERE name=\"%@\"",txtName.text];

    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(_contactDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
            NSString *roll = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
            txtroll.text = roll;
            NSString *age = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
            sldAge.value = [age floatValue];
           NSLog(@"Match found");
        } else {
           NSLog(@"Match found");
            txtroll.text = @"";
            sldAge.value = 0.0;
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(_contactDB);
}

}