sqlite3学习
发布时间:2020-12-12 23:45:58 所属栏目:百科 来源:网络整理
导读:/prepre name="code" class="objc" /prepre name="code" class="objc" /prepre name="code" class="objc"#import "ViewController.h"#import "sqlite3.h"@interface ViewController ()- (IBAction)insert:(id)sender;- (IBAction)delete:(id)sender;- (IBAct
</pre><pre name="code" class="objc"> </pre><pre name="code" class="objc"> </pre><pre name="code" class="objc">#import "ViewController.h" #import "sqlite3.h" @interface ViewController () - (IBAction)insert:(id)sender; - (IBAction)delete:(id)sender; - (IBAction)update:(id)sender; @property (nonatomic,assign) sqlite3 *db; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // NSString *name = [NSString stringWithFormat:@""]; //NSString *sql = [NSString stringWithFormat:@"insert into t_class (name) valus] // Do any additional setup after loading the view,typically from a nib. NSString *path = NSHomeDirectory();//主目录 NSLog(@"NSHomeDirectory:%@",path); NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0]; NSString *filePath = [cachePath stringByAppendingString:@"student.sqlite"]; sqlite3 *db = nil; if (sqlite3_open(filePath.UTF8String,&db)== SQLITE_OK) { NSLog(@"success"); }else{ NSLog(@"failed"); } _db = db; NSString *sql = @"create table t_makeup (id integer primary key autoincrement,name text)"; [self execWithsql:sql]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)insert:(id)sender { NSString *sql = @"insert into t_makeup (name) values ('zhangsan');"; [self execWithsql:sql]; } - (IBAction)delete:(id)sender { NSString *sql = @"delete from t_makeup"; [self execWithsql:sql]; } - (IBAction)update:(id)sender { NSString *sql = @"update t_makeup set name = 'zhangsan'"; [self execWithsql:sql]; } - (IBAction)select:(id)sender { NSString *sql = @"select * from t_makeup"; sqlite3_stmt *stmt; if(sqlite3_prepare_v2(_db,sql.UTF8String,-1,&stmt,NULL)==SQLITE_OK) { NSLog(@"success"); if (sqlite3_step(stmt) == SQLITE_ROW) { NSString *name = [NSString stringWithUTF8String: sqlite3_column_text(stmt,1) ]; NSLog(@"%@",name); } } } -(void)execWithsql:(NSString *)sql//抽取的方法 { char *errmsg; sqlite3_exec(_db,NULL,&errmsg); if (errmsg) { NSLog(@"failed"); }else { NSLog(@"success"); } } @end
以上是基本的在xcode中实现sqlite的insert create update delete 等基本操作。
PS 今天遇到的几个小问题: 1,xcode nslog打印不出来是因为没把控制台调出来orz。。 解决方案:command shift +c 2,数据库无法同步问题 解决方案:不要写table。。直接上表名 3.db赋值为0 必须将_db = db写在创建了表的代码之后!!! </pre><pre name="code" class="objc"> sqlite3 *db = nil; if (sqlite3_open(filePath.UTF8String,&db)== SQLITE_OK) { NSLog(@"success"); }else{ NSLog(@"failed"); } _db = db; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |