{"id":190932,"date":"2022-10-11T00:17:25","date_gmt":"2022-10-10T16:17:25","guid":{"rendered":"https:\/\/www.idc.net\/help\/190932\/"},"modified":"2022-10-11T00:17:25","modified_gmt":"2022-10-10T16:17:25","slug":"%e5%90%8e%e6%b5%aa%e4%ba%91ios%e6%95%99%e7%a8%8b%ef%bc%9aios-sqlite%e6%95%b0%e6%8d%ae%e5%ba%93","status":"publish","type":"post","link":"https:\/\/idc.net\/help\/190932\/","title":{"rendered":"\u540e\u6d6a\u4e91IOS\u6559\u7a0b\uff1aiOS SQLite\u6570\u636e\u5e93"},"content":{"rendered":"<h2>IOS SQLite\u6570\u636e\u5e93<\/h2>\n<hr>\n<h2>\u7b80\u4ecb<\/h2>\n<p>\u5728IOS\u4e2d\u4f7f\u7528Sqlite\u6765\u5904\u7406\u6570\u636e\u3002\u5982\u679c\u4f60\u5df2\u7ecf\u4e86\u89e3\u4e86SQL\uff0c\u90a3\u4f60\u53ef\u4ee5\u5f88\u5bb9\u6613\u7684\u638c\u63e1SQLite\u6570\u636e\u5e93\u7684\u64cd\u4f5c\u3002<\/p>\n<h3>\u5b9e\u4f8b\u6b65\u9aa4<\/h3>\n<p>1\u3001\u521b\u5efa\u4e00\u4e2a\u7b80\u5355\u7684View based application<\/p>\n<p>2\u3001\u9009\u62e9\u9879\u76ee\u6587\u4ef6\uff0c\u7136\u540e\u9009\u62e9\u76ee\u6807\uff0c\u6dfb\u52a0libsqlite3.dylib\u5e93\u5230\u9009\u62e9\u6846\u67b6<\/p>\n<p>3\u3001\u901a\u8fc7\u9009\u62e9\" File-&gt; New -&gt; File... -&gt; \"\u9009\u62e9 Objective C class \u521b\u5efa\u65b0\u6587\u4ef6\uff0c\u5355\u51fb\u4e0b\u4e00\u6b65<\/p>\n<p>4\u3001\"sub class of\"\u4e3aNSObject\"\uff0c\u7c7b\u547d\u540d\u4e3aDBManager<\/p>\n<p>5\u3001\u9009\u62e9\u521b\u5efa<\/p>\n<p>6\u3001\u66f4\u65b0DBManager.h,\u5982\u4e0b\u6240\u793a<\/p>\n<pre>#import &lt;Foundation\/Foundation.h&gt;\n#import &lt;sqlite3.h&gt;\n\n@interface DBManager : NSObject\n{\n    NSString *databasePath;\n}\n\n+(DBManager*)getSharedInstance;\n-(BOOL)createDB;\n-(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name \n  department:(NSString*)department year:(NSString*)year;\n-(NSArray*) findByRegisterNumber:(NSString*)registerNumber;\n\n@end\n<\/pre>\n<p>7\u3001\u66f4\u65b0DBManager.m,\u5982\u4e0b\u6240\u793a<\/p>\n<pre>#import \"DBManager.h\"\nstatic DBManager *sharedInstance = nil;\nstatic sqlite3 *database = nil;\nstatic sqlite3_stmt *statement = nil;\n\n@implementation DBManager\n\n+(DBManager*)getSharedInstance{\n    if (!sharedInstance) {\n        sharedInstance = [[super allocWithZone:NULL]init];\n        [sharedInstance createDB];\n    }\n    return sharedInstance;\n}\n\n-(BOOL)createDB{\n    NSString *docsDir;\n    NSArray *dirPaths;    \n    \/\/ Get the documents directory\n    dirPaths = NSSearchPathForDirectoriesInDomains\n    (NSDocumentDirectory, NSUserDomainMask, YES);    \n    docsDir = dirPaths[0];\n    \/\/ Build the path to the database file\n    databasePath = [[NSString alloc] initWithString: \n    [docsDir stringByAppendingPathComponent: @\"student.db\"]];\n    BOOL isSuccess = YES;\n    NSFileManager *filemgr = [NSFileManager defaultManager];    \n    if ([filemgr fileExistsAtPath: databasePath ] == NO)\n    {\n        const char *dbpath = [databasePath UTF8String];        \n        if (sqlite3_open(dbpath, &amp;database) == SQLITE_OK)\n        {\n            char *errMsg;\n            const char *sql_stmt =\n            \"create table if not exists studentsDetail (regno integer \n            primary key, name text, department text, year text)\";            \n            if (sqlite3_exec(database, sql_stmt, NULL, NULL, &amp;errMsg) \n               != SQLITE_OK)\n            {\n                isSuccess = NO;\n                NSLog(@\"Failed to create table\");\n            }\n            sqlite3_close(database);\n            return  isSuccess;\n        }\n        else {\n            isSuccess = NO;\n            NSLog(@\"Failed to open\/create database\");\n        }\n    }    \n    return isSuccess;\n}\n\n- (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name \n  department:(NSString*)department year:(NSString*)year;\n{\n    const char *dbpath = [databasePath UTF8String];    \n    if (sqlite3_open(dbpath, &amp;database) == SQLITE_OK)\n    {        \n        NSString *insertSQL = [NSString stringWithFormat:@\"insert into\n        studentsDetail (regno,name, department, year) values\n        (\\\"%d\\\",\\\"%@\\\", \\\"%@\\\", \\\"%@\\\")\",[registerNumber integerValue],\n        name, department, year];        \n        const char *insert_stmt = [insertSQL UTF8String];\n        sqlite3_prepare_v2(database, insert_stmt,-1, &amp;statement, NULL);\n        if (sqlite3_step(statement) == SQLITE_DONE)\n        {\n            return YES;\n        } \n        else {\n            return NO;\n        }\n        sqlite3_reset(statement);\n    }\n    return NO;\n}\n\n- (NSArray*) findByRegisterNumber:(NSString*)registerNumber\n{\n    const char *dbpath = [databasePath UTF8String];    \n    if (sqlite3_open(dbpath, &amp;database) == SQLITE_OK)\n    {\n        NSString *querySQL = [NSString stringWithFormat:\n        @\"select name, department, year from studentsDetail where \n        regno=\\\"%@\\\"\",registerNumber];        \n        const char *query_stmt = [querySQL UTF8String];\n        NSMutableArray *resultArray = [[NSMutableArray alloc]init];\n        if (sqlite3_prepare_v2(database,\n           query_stmt, -1, &amp;statement, NULL) == SQLITE_OK)\n        {\n            if (sqlite3_step(statement) == SQLITE_ROW)\n            {                \n                NSString *name = [[NSString alloc] initWithUTF8String:\n                 (const char *) sqlite3_column_text(statement, 0)];\n                [resultArray addObject:name];\n                NSString *department = [[NSString alloc] initWithUTF8String:\n                (const char *) sqlite3_column_text(statement, 1)];\n                [resultArray addObject:department];\n                NSString *year = [[NSString alloc]initWithUTF8String:\n                (const char *) sqlite3_column_text(statement, 2)];\n                [resultArray addObject:year];\n                return resultArray;\n            }\n            else{\n                NSLog(@\"Not found\");\n                return nil;\n            }\n            sqlite3_reset(statement);\n        }\n    }\n    return nil;\n}\n<\/pre>\n<p>8\u3001\u5982\u56fe\u6240\u793a\uff0c\u66f4\u65b0ViewController.xib\u6587\u4ef6<\/p>\n<p style=\"text-align: center\"><img decoding=\"async\" src=\"https:\/\/atts.IDC.NET.cn\/attachments\/day_171121\/201711211704126702.jpg\" class=\"aligncenter\"><\/p>\n<p>9\u3001\u4e3a\u4e0a\u8ff0\u6587\u672c\u5b57\u6bb5\u521b\u5efaIBOutlets<\/p>\n<p>10\u3001\u4e3a\u4e0a\u8ff0\u6309\u94ae\u521b\u5efaIBAction<\/p>\n<p>11\u3001\u5982\u4e0b\u6240\u793a\uff0c\u66f4\u65b0ViewController.h<\/p>\n<pre>#import &lt;UIKit\/UIKit.h&gt;\n#import \"DBManager.h\"\n\n@interface ViewController : UIViewController&lt;UITextFieldDelegate&gt;\n{\n    IBOutlet UITextField *regNoTextField;\n    IBOutlet UITextField *nameTextField;\n    IBOutlet UITextField *departmentTextField;\n    IBOutlet UITextField *yearTextField;\n    IBOutlet UITextField *findByRegisterNumberTextField;\n    IBOutlet UIScrollView *myScrollView;\n}\n\n-(IBAction)saveData:(id)sender;\n-(IBAction)findData:(id)sender;\n\n@end\n<\/pre>\n<p>12\u3001\u66f4\u65b0ViewController.m,\u5982\u4e0b\u6240\u793a<\/p>\n<pre>#import \"ViewController.h\"\n\n@interface ViewController ()\n\n@end\n\n@implementation ViewController\n\n- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)\n  nibBundleOrNil\n{\n    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];\n    if (self) {\n        \/\/ Custom initialization\n    }\n    return self;\n}\n\n- (void)viewDidLoad\n{\n    [super viewDidLoad];\n    \/\/ Do any additional setup after loading the view from its nib.\n}\n\n- (void)didReceiveMemoryWarning\n{\n    [super didReceiveMemoryWarning];\n    \/\/ Dispose of any resources that can be recreated.\n}\n\n-(IBAction)saveData:(id)sender{\n    BOOL success = NO;\n    NSString *alertString = @\"Data Insertion failed\";\n    if (regNoTextField.text.length&gt;0 &amp;&amp;nameTextField.text.length&gt;0 &amp;&amp;\n    departmentTextField.text.length&gt;0 &amp;&amp;yearTextField.text.length&gt;0 )\n    {\n        success = [[DBManager getSharedInstance]saveData:\n        regNoTextField.text name:nameTextField.text department:\n        departmentTextField.text year:yearTextField.text];\n    }\n    else{\n        alertString = @\"Enter all fields\";\n    }     \n    if (success == NO) {\n        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:\n        alertString message:nil\n        delegate:nil cancelButtonTitle:@\"OK\" otherButtonTitles:nil];\n        [alert show];\n    }\n}\n\n-(IBAction)findData:(id)sender{\n    NSArray *data = [[DBManager getSharedInstance]findByRegisterNumber:\n    findByRegisterNumberTextField.text];\n    if (data == nil) {\n        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:\n        @\"Data not found\" message:nil delegate:nil cancelButtonTitle:\n        @\"OK\" otherButtonTitles:nil];\n        [alert show];\n        regNoTextField.text = @\"\";\n        nameTextField.text =@\"\";\n        departmentTextField.text = @\"\";\n        yearTextField.text =@\"\";\n    }\n    else{\n        regNoTextField.text = findByRegisterNumberTextField.text;\n        nameTextField.text =[data objectAtIndex:0];\n        departmentTextField.text = [data objectAtIndex:1];\n        yearTextField.text =[data objectAtIndex:2];\n    }\n}\n\n#pragma mark - Text field delegate\n-(void)textFieldDidBeginEditing:(UITextField *)textField{\n    [myScrollView setFrame:CGRectMake(10, 50, 300, 200)];\n    [myScrollView setContentSize:CGSizeMake(300, 350)];\n}\n-(void)textFieldDidEndEditing:(UITextField *)textField{\n    [myScrollView setFrame:CGRectMake(10, 50, 300, 350)];\n\n}\n-(BOOL) textFieldShouldReturn:(UITextField *)textField{\n    \n    [textField resignFirstResponder];\n    return YES;\n}\n@end\n<\/pre>\n<h3>\u8f93\u51fa<\/h3>\n<p>\u73b0\u5728\u5f53\u6211\u4eec\u8fd0\u884c\u5e94\u7528\u7a0b\u5e8f\u65f6\uff0c\u6211\u4eec\u5c31\u4f1a\u83b7\u5f97\u4e0b\u9762\u7684\u8f93\u51fa\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u5176\u4e2d\u6dfb\u52a0\u53ca\u67e5\u627e\u5b66\u751f\u7684\u8be6\u7ec6\u4fe1\u606f<\/p>\n<p style=\"text-align: center\"><img decoding=\"async\" src=\"https:\/\/atts.IDC.NET.cn\/attachments\/day_171121\/201711211704231025.jpg\" class=\"aligncenter\"><\/p>\n<p style=\"text-align: center\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>IOS SQLite\u6570\u636e\u5e93 \u7b80\u4ecb \u5728IOS\u4e2d\u4f7f\u7528Sqlite\u6765\u5904\u7406\u6570\u636e\u3002\u5982\u679c\u4f60\u5df2\u7ecf\u4e86\u89e3\u4e86SQL\uff0c\u90a3\u4f60\u53ef\u4ee5\u5f88\u5bb9\u6613 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":190933,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[189686],"tags":[],"class_list":["post-190932","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ios"],"_links":{"self":[{"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/posts\/190932","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/comments?post=190932"}],"version-history":[{"count":0,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/posts\/190932\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/media\/190933"}],"wp:attachment":[{"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/media?parent=190932"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/categories?post=190932"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/idc.net\/help\/wp-json\/wp\/v2\/tags?post=190932"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}