在xcode中将日期插入sqlite3数据库

时间:2014-09-25 18:46:03

标签: ios xcode sqlite

我正在关注此链接http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_7_Application中显示的示例 我希望我的数据库存储几个列,这些列将保存日期信息,如出生日期以及一些文本字段。  我的代码看起来像这样: DatabaseViewController.h:

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

@interface DatabaseViewController : UIViewController

@property (strong, nonatomic) IBOutlet UITextField *name;
@property (strong, nonatomic) IBOutlet UITextField *surname1;
@property (strong, nonatomic) IBOutlet UITextField *surname2;
@property (strong, nonatomic) IBOutlet UITextField *telephone;
@property (strong, nonatomic) IBOutlet UITextField *email;
@property (strong, nonatomic) IBOutlet UITextField *address;
@property (strong, nonatomic) IBOutlet UITextField *bloodType;
@property (strong, nonatomic) IBOutlet UITextField *allergies;
 @property (strong, nonatomic) IBOutlet UITextField *fatherName;
@property (strong, nonatomic) IBOutlet UITextField *motherName;
@property (strong, nonatomic) IBOutlet UIDatePicker *dob;
@property (strong, nonatomic) IBOutlet UIDatePicker *wedding;
@property (strong, nonatomic) IBOutlet UIDatePicker *feastDay;
@property (strong, nonatomic) IBOutlet UIDatePicker *otherDates;
@property (strong, nonatomic) IBOutlet UILabel *status;

- (IBAction)saveData:(id)sender;
- (IBAction)findDATA:(id)sender;


  @property (strong, nonatomic) NSString *databasePath;
  @property (nonatomic) sqlite3 *contactDB;

  @end

和databaseviewcontroller.m看起来像这样:

    #import "DatabaseViewController.h"

   @interface DatabaseViewController ()




   @end

   @implementation DatabaseViewController

   - (void)viewDidLoad
    {
     [super 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:
                                  @"contacts.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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME1 TEXT, SURNAME2 TEXT, TELEPHONE TEXT, EMAIL TEXT, ADDRESS TEXT, BLOODTYPE TEXT, ALLERGIES TEXT, FATHERNAME TEXT, MOTHERNAME TEXT, DOB DATETIME, WEDDING DATETIME, FEASTDAY DATETIME, OTHERDATES DATETIME)";


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

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



if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{


    NSString *insertSQL = [NSString stringWithFormat:
                           @"INSERT INTO CONTACTS date values (name, surname1, surname2, telephone, email, address, bloodType, allergies, fatherName, motherName, dob, wedding, feastDay, otherDATES ) VALUES (\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\",\"%@\", \"%@\", \"%@\",\"%@\", \"%d\", \"%d\",\"%d\",\"%d\")",
                           _name.text, _surname1.text, _surname2.text, _telephone.text, _email.text, _address.text, _bloodType.text,_allergies.text, _fatherName.text, _motherName.text, _dob.datePickerMode,_wedding.datePickerMode, _feastDay.datePickerMode, _otherDates.datePickerMode];

    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 = @"";
        _surname1.text = @"";
        _surname2.text = @"";
        _telephone.text = @"";
        _email.text = @"";
        _address.text = @"";
        _bloodType.text = @"";
        _allergies.text = @"";
        _fatherName.text = @"";
        _motherName.text = @"";
        _dob.date = @"";
        _wedding.date = @"";
        _feastDay.date = @"";
        _otherDates.date = @"";

    } else {
        _status.text = @"Failed to add contact";
    }
    sqlite3_finalize(statement);
    sqlite3_close(_contactDB);
}
}

 - (void)didReceiveMemoryWarning
 {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }



 @end

出现的错误显示“从NSString *分配给NSDATE *的不兼容指针类型”。 那么插入日期需要做些什么呢? 提前谢谢你,我希望每个人都过得愉快!

2 个答案:

答案 0 :(得分:1)

我认为您可以使用此方法[[NSDate date] timeIntervalSince1970];并将日期存储为数据库中的双倍。

此外,您正在尝试将空NSString @""分配给NSDate属性:

_dob.date = @"";
_wedding.date = @"";
_feastDay.date = @"";
_otherDates.date = @"";

这是不正确的,如果您需要重置这些值,则应将其设置为nil或特定NSDate值,例如[NSDate date]; 尝试将其更改为以下代码:

_dob.date = nil;
_wedding.date = nil;
_feastDay.date = nil;
_otherDates.date = nil;

答案 1 :(得分:0)

使用Sqlite插入注册用户

  • (IBAction为)registerButtonClick:(ID)发送方 {

    NSString * a,* b; A = _passWordTxtf.text; B = _confirmPassWordTxtf.text;

    if(([_ userNameTxtf.text isEqualToString:@“”])||([_ userEmailTxtf.text isEqualToString:@“”])||([_ passWordTxtf.text isEqualToString:@“”] ||([_ confirmPassWordTxtf。 text isEqualToString:@“”]))) {     UIAlertView * infoAlert = [[UIAlertView alloc] initWithTitle:@“Warning”消息:@“请填写所有详细信息”委托:self cancelButtonTitle:@“Ok”otherButtonTitles:nil];

    [infoAlert show];
    

    } 其他 {     if([a isEqualToString:b])     {

        NSArray *dir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
        NSString *dbPath=[NSString stringWithFormat:@"%@/userInfoDb.sqlite",[dir lastObject]];
    
        sqlite3 *db;
    
        if (sqlite3_open([dbPath UTF8String],&db)==SQLITE_OK)
        {
    
            NSString *query=[NSString stringWithFormat:@"insert into user values(\"%@\",\"%@\",\"%@\")",_userNameTxtf.text,_userEmailTxtf.text,_passWordTxtf.text];
    
            const char *q=[query UTF8String];
    
    
            if (sqlite3_exec(db, q, NULL, NULL, NULL)==SQLITE_OK)
            {
                NSLog(@"User registred successfully");
            }
            else
            {
                NSLog(@"User registration failed");
            }
    
        }
        else
        {
            NSLog(@"Db Open Falied while saving");
        }
        sqlite3_close(db);
    
        UIAlertView *sucessAlert = [[UIAlertView alloc] initWithTitle:@"Sucessfull" message:@"User is Registered" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    
        [sucessAlert show];
    
        _userNameTxtf.text=@"";
        _userEmailTxtf.text=@"";
        _passWordTxtf.text=@"";
        _confirmPassWordTxtf.text=@"";
    
    }
    else
    {
        UIAlertView *registerAlert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Password Doesn't Match" delegate:self cancelButtonTitle:@"Re Enter" otherButtonTitles:nil];
    
        [registerAlert show];
        _passWordTxtf.text=@"";
        _confirmPassWordTxtf.text=@"";
    }
    

    }

}