从sqlite数据库存储和检索数据

时间:2011-11-16 06:15:07

标签: iphone sqlite save

我正在构建一个包含一个视图中的表单的应用程序,其中用户填充所有字段,当他单击保存按钮时,数据必须保存到数据库中,并且在导航回来之后,还有另一个视图,当输入后,必须显示已保存的数据(事件)。

我创建了一个数据库,并经历了几个sqlite3教程;

我已根据我的要求对代码进行了所有其他更改。但是,当我使用此语句检查数据是否插入数据库时​​:

SELECT * FROM reminders;

我什么都没得到,我对是否插入数据感到困惑。

如何正确保存,如何从数据库中检索数据并在其他视图中显示?

5 个答案:

答案 0 :(得分:4)

首先,您应该创建sqlite3数据库文件(check this link),然后将其包含在项目中。现在要连接到它,您可以使用以下代码:

#pragma mark -
#pragma mark Create/Load Database
+ (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"DATABASENAME.DB"];

    BOOL success;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) {
        return;
    }

    // The writable database does not exist, so copy the default to the appropriate location.
    NSError * error;
    NSString * defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DATABASENAME.DB"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}
+ (sqlite3 *)getDBConnection {
    [DatabaseController createEditableCopyOfDatabaseIfNeeded];

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:@"DATABASENAME.DB"];

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

然后插入记录即可使用此代码:

+ (void)insertEvent:(Event *)newEvent {
    sqlite3 * connection = [DatabaseController getDBConnection];
    const char * text = "INSERT INTO Event (Serial, Name, Date) VALUES (?, ?, ?)";
    sqlite3_stmt * insert_statement;
    int prepare_result = sqlite3_prepare_v2(connection, text, -1, &insert_statement, NULL);
    if ((prepare_result != SQLITE_DONE) && (prepare_result != SQLITE_OK)) {
        // Error
        sqlite3_close(connection);
        return;
    }

    sqlite3_bind_int(insert_statement, 1, newEvent.Serial);
    sqlite3_bind_text(insert_statement, 2, [newEvent.Name UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_double(insert_statement, 3, [newEvent.Date timeIntervalSince1970]);

    int statement_result = sqlite3_step(insert_statement);
    if ((statement_result != SQLITE_DONE) && (statement_result != SQLITE_OK)) {
        //Error
        sqlite3_close(connection);
        return;
    }

    sqlite3_finalize(insert_statement);

    // Get the Id of the inserted event
    int rowId = sqlite3_last_insert_rowid(connection);
    newEvent.Id = rowId;

    sqlite3_close(connection);
}

现在要举办活动:

+ (Event *)getEventById:(int)id {
    Event * result = nil;
    sqlite3 * connection = [DatabaseController getDBConnection];

    const char * text = "SELECT * FROM Event WHERE Id = ?";
    sqlite3_stmt * select_statement;

    int prepare_result = sqlite3_prepare_v2(connection, text, -1, &select_statement, NULL);
    if ((prepare_result != SQLITE_DONE) && (prepare_result != SQLITE_OK)) {
        // error
        sqlite3_close(connection);
        return result;
    }

    sqlite3_bind_int(select_statement, 1, id);

    if (sqlite3_step(select_statement) == SQLITE_ROW) {
        result = [[[Event alloc] init] autorelease];

        result.Id = sqlite3_column_int(select_statement, 0);
        result.Serial = sqlite3_column_int(select_statement, 1);
        result.Name = (((char *) sqlite3_column_text(select_statement, 2)) == NULL)? nil:[NSString stringWithUTF8String:((char *) sqlite3_column_text(select_statement, 2))];
        result.Date = [NSDate dateWithTimeIntervalSince1970:sqlite3_column_double(select_statement, 3)];
    }
    sqlite3_finalize(select_statement);

    sqlite3_close(connection);
    return (result);
}

答案 1 :(得分:1)

这是一篇博文,应该让你指出正确的方向,对我来说非常有用,所以与你分享。:P

http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/

答案 2 :(得分:1)

您可以通过检查数据库表来检查您的数据是否已保存。转到用户>您的计算机名称>库>应用程序支持> iphone模拟器> 4.3(您的ios版本)>应用程序..然后查找您的应用程序,转到文档并打开sqlite文件。在这里你可以看到数据。

答案 3 :(得分:0)

您应该使用FMDB来降低代码的复杂性。

它是围绕SQLite的Objective-C包装器。

FMDB on github

答案 4 :(得分:0)

此代码用于存储数据并从sqlite数据库中检索数据 首先,您只需在objective-c

中编写下面的代码后添加sqlite3框架工作

ViewController.h

   #import <UIKit/UIKit.h>
   #import "sqlite3.h"
  @interface ViewController : UIViewController

  @property (weak, nonatomic) IBOutlet UITextField *firstName;
  @property (weak, nonatomic) IBOutlet UITextField *lastName;
  @property (weak, nonatomic) IBOutlet UITextField *state;
 @property (weak, nonatomic) IBOutlet UITextField *mobileNum;

 - (IBAction)saveButton:(id)sender;


- (IBAction)featchButton:(id)sender;
 @property (weak, nonatomic) IBOutlet UILabel *label;

 @property NSString *myDatabase;
 @property sqlite3 *marksDB;

ViewController.m

         #import "ViewController.h"

          @interface ViewController ()

           @end

           @implementation ViewController

      - (void)viewDidLoad {
      [super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;

dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);


docsDir=dirPaths[0];

_myDatabase=[[NSString alloc]initWithString:[docsDir stringByAppendingString:@"marks.db"]];
NSLog(@"My Data base %@",_myDatabase);

NSFileManager *fileMgr=[NSFileManager defaultManager];
if ([fileMgr fileExistsAtPath:_myDatabase]==NO)
{
    const char *dbpath=[_myDatabase UTF8String];

    if (sqlite3_open(dbpath, &_marksDB)==SQLITE_OK)
    {
        char *errMsg;


     const char *sql_stmt="CREATE TABLE IF NOT EXISTS MARKS(ID INTEGER     PRIMARY KEY AUTOINCREMENT ,FIRST NAME TEXT,LAST NAME TEXT,STATE TEXT,MOBILE INTEGER  )";

        if (sqlite3_exec(_marksDB, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK)
        {
          _label.text=@"Failed to create Table";
        }
        sqlite3_close(_marksDB);
    }
    else
    {
         _label.text=@"Failed to Create/Open Database";
    }
}

}

        - (IBAction)saveButton:(id)sender {
        sqlite3_stmt *statement;
const char *dbpath=[_myDatabase UTF8String];
if (sqlite3_open(dbpath, &_marksDB)==SQLITE_OK)
{
    NSString *insertSQL=[NSString stringWithFormat:@"INSERT INTO MARKS(firstname,lastname,state,mobile )VALUES(\"%@\",\"%@\",\"%@\",\"%@\")",_firstName.text,_lastName.text,_state.text,_mobileNum.text ];
    const char *insert_stmt=[insertSQL UTF8String];

    sqlite3_prepare_v2(_marksDB, insert_stmt, -1, &statement, NULL);
    if (sqlite3_step(statement)==SQLITE_DONE)
    {
       _label.text=@"Contact Added";
        _firstName.text=@"";
       _lastName.text=@"";
       _state.text=@"";
       _mobileNum.text=@"";

    }
    else
    {
        _label.text=@"Failed to Add Contact";
    }
    sqlite3_finalize(statement);
    sqlite3_close(_marksDB);

}

}

      - (IBAction)featchButton:(id)sender {
         const char *dbpath=[_myDatabase UTF8String];
        sqlite3_stmt *statement;
           if (sqlite3_open(dbpath, &_marksDB)==SQLITE_OK)

{

    NSString *query=[NSString stringWithFormat:@"SELECT firstname,lastname,state,mobile,  FROM MARKS WHERE firstname=\"%@\"",_firstName.text];
    const char *query_stmt=[query UTF8String];
    if (sqlite3_prepare_v2(_marksDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
    {
        if (sqlite3_step(statement)==SQLITE_ROW)
        {
            NSString *first=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
            _firstName.text=first;

            NSString *lastName=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
           _lastName.text=lastName;

            NSString *state=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
            _state.text=state;
            NSString *mobile=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
            _mobileNum.text=mobile;


           _label.text=@"Match Found";





        }
        else
        {
           _label.text=@"Not Matched";
            _lastName.text=@"";
            _state.text=@"";
            _mobileNum.text=@"";
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(_marksDB);
}


 }
  @end