Swift 操作数据库
操作数据库
以一个实例展示输入名称和年龄保存到数据库,然后在另外一个tab里面显示,围绕一个TableView 来完成一个对数据的增、删、改、查的操作 。
具体实现代码:
1:创建工程的时候需要选择Use Core Data 使用数据库是Sqlit。
2:导入
CoreData
3:定义对象读取数据库:
NSManagedObjectContext
4:创建表:创建表的时候首写字母一定是大写不然会提示出错
5:获取数据连接,相当于创建一个连接池connection,用这个对象就可以保存,查询数据。
context= (UIApplication.sharedApplication().delegateas!AppDelegate).managedObjectContext
6:创建访问表的变量。
7:设置字段值:
varrow:AnyObject =NSEntityDescription.insertNewObjectForEntityForName("USERS",inManagedObjectContext:context!) if(name.text.isEmpty){ UIAlertView(title:"提示",message:姓名不能为空nil,cancelButtonTitle:确认").show() name.becomeFirstResponder()//得到焦点 return } row.setValue(text,forKey:"name") iflet_age =age.text.toInt() { 可以根据此种方法判断是否是int类型 var_age:Int =toInt()! if(_age <0){ 年龄必须为正数 age() return } row.setValue(_age,27)">"age") }else{ () return }
8:保存操作,保存数据
context?.save(nil)
9:读取数据:将数据读取到NString
).managedObjectContext!
dataarry=context.executeFetchRequest(NSFetchRequest(entityName:"USERS"),error:nil)!
10:打开表可以看到我们保存的数据:(大家可以去网上下载Sqlit工具,我用的Navict 感觉很不错的支持mysql、orcal、sqlit 等)
11:更新数据: @IBActionfuncupdate(sender:AnyObject) { data.setValue(_uname."name") _uage.toInt(),27)">"age") data.managedObjectContext) dismissViewControllerAnimatedtrue,completion:) 12:删除 / Override to support editing the table view. overridefunctableView(tableView:UITableView,commitEditingStyle editingStyle:UITableViewCellEditingStyle,forRowAtIndexPath indexPath:NSIndexPath) { ifeditingStyle == .Delete{ // Delete the row from the data source //tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: .Fade) deleteObject(dataarry[indexPath.row]as!NSManagedObject) save(nil); refreshData() }elseInsert{ // Create a new instance of the appropriate class,insert it into the array,and add a new row to the table view } } importUIKit importCoreData classViewController:UIViewController{ @IBOutletweakvarage:UITextField! name:! var context:NSManagedObjectContext! funcviewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. context).managedObjectContext } funcdidReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } funcsaveAction(sender:AnyObject) { return } context?.nil) .resignFirstResponder第一响应事件取消,消除键盘操作 } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |