sqlite数据库的一些操作和core data的操作

应用程序接口的解释

http://www.xuebuyuan.com/321813.html

打开数据库的一些操作

sqlite3_open

创建数据库表

sqlite3_exec

关闭数据库 sqlite3_close

if sqlite3_open(path, &db) != SQLITE_OK {
            print("error")
        }
        //创建表的过程
        let string = "CREATE TABLE IF NOT EXISTS PERSONINFO (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT)";
        let cString = string.cStringUsingEncoding(NSUTF8StringEncoding)
        if(sqlite3_exec(db, cString!, nil, nil, nil) != SQLITE_OK) {
            print("失败")
        }
        sqlite3_close(db)


查询数据的过程 

sqlite3_open打开数据库

sqlite3_prepare_v2函数预处理sql语句 转化成二进制代码 更高速的执行

sqlite3_step执行sql语句,遍历结果集

sqlite3_column_text函数提取字段的数据

sqlite3_finalize或者sqlite3_close释放资源

 var cpath = document!.stringByAppendingPathComponent("personinfo.sqlite")

         if sqlite3_open(cpath, &db) != SQLITE_OK{
            print("error")
         }else {
            var statement = COpaquePointer()
            //查询的sql语句 ?代表要绑定的参数
            let sql = "SELECT cdate,content FROM Note where cdate = ?"
            let csql = sql.cStringUsingEncoding(NSUTF8StringEncoding)
            //预处理sql语句 将sql编译成二进制代码 提高sql语句的执行速度 第三个参数代表全部sql字符串的长度 第4个参数是地址 是语句对象 通过语句对象可以执行sql语句 第5个参数是sql语句没有执行的部分语句
            if sqlite3_prepare_v2(db, csql!, -1, &statement, nil) == SQLITE_OK{
                let dateFormetter = NSDateFormatter()
                dateFormetter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                var strDate = "string"
                let cDate = strDate.cStringUsingEncoding(NSUTF8StringEncoding)
             //绑定参数 第一个参数是statement指针 第二个参数为序号 从1开始 第3个参数是字符串的值  第4个参数为字符串的长度 第5个参数是函数指针
            sqlite3_bind_text(statement, 1, cDate!, -1, nil)
                //执行 若返回值是SQLITE_ROW 代表还有其他的行没有遍历
                sqlite3_step(statement)
            }

修改数据的过程

sqlite3_open打开数据库

sqlite3_prepare_v2函数预处理sql语句

sqlite3_bind_text绑定参数

sqlite3_step执行语句

sqlite3_finalize或者sqlite3_close关闭数据库

以下是插入的一些操作 还有一点错误 以后改正

 //插入数据的过程
let insert1 = "INSERT INTO personinfo (name,age,address) VALUES ('caokaiqiang', '14', 'zhejiang')"
        if sqlite3_exec(db, insert1.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) != SQLITE_OK{
            print("error")
        }

通过core data来创建数据 主要通过上下文的context来进行数据的插入 删除 还有查询 注意查询的时候 返回的是一对数组 为[NSManagedObject] 所以可以用valueForKey来提取

import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDataSource {
    var managedContext:NSManagedObjectContext!
    var people = [NSManagedObject]()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        title = "\"The List\""
      tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        let image = UIImage(named: "1")
        let photoData = UIImagePNGRepresentation(image!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
//实现数据源
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        let person = people[indexPath.row]
        cell.textLabel?.text = person.valueForKey("name") as? String
        return cell
    }
    @IBAction func addName(sender: UIBarButtonItem) {
    let alert = UIAlertController(title: "New Name", message: "addNewName", preferredStyle: .Alert)
        let alertAction = UIAlertAction(title: "addNewName", style: .Default) { (action:UIAlertAction) -> Void in
            let textField = alert.textFields![0] as UITextField
            self.saveName(textField.text!)
            self.tableView.reloadData()
        }
    alert.addTextFieldWithConfigurationHandler(nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    alert.addAction(alertAction)
    alert.addAction(cancelAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    func saveName(name:String) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        //托管对象文本认为是在内存中暂存的管理对象
        let managedContext = appDelegate.managedObjectContext
        let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
        person.setValue(name, forKey: "name")
        do { try managedContext.save()
        }catch{
            print("error")
        }
        people.append(person)
    }
    //读取数据
    override func viewWillAppear(animated: Bool) {
        //托管对象文本认为是在内存中暂存的管理对象
        var fetchedResults = [NSManagedObject]()
      
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        //读取数据的类 是一个修饰语
        
             let fetchRequest = NSFetchRequest(entityName: "Person")
        
     
        //处理请求
        do { fetchedResults =  try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
        }catch{
            print("error")
        }
      people = fetchedResults
    }
}
通过fetchResultController 将core data和tableview联系起来

import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var managedContext:NSManagedObjectContext!
    var fetchedResultsController:NSFetchedResultsController!
    override func viewDidLoad() {
         var app = UIApplication.sharedApplication().delegate as! AppDelegate
        self.managedContext = app.managedObjectContext
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    //创建fetch request
        let entity = NSEntityDescription.entityForName("Team", inManagedObjectContext: managedContext)
        let team = Team(entity: entity!, insertIntoManagedObjectContext: managedContext)
        team.teamName = "cao"
        managedContext.performBlock { () -> Void in
            do { try  self.managedContext.save()
            }catch{
                print("error")
            }

     
        let sort = NSSortDescriptor(key: "teamName", ascending: true)
        let fetchRequest = NSFetchRequest(entityName: "Team")
        fetchRequest.sortDescriptors = [sort]
        //创建controller 
        self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedContext, sectionNameKeyPath: nil, cacheName: nil)
        do { try self.fetchedResultsController.performFetch()
        }catch{
            print("加载失败")
        }
    }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return (fetchedResultsController.sections?.count)!
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionInfo = fetchedResultsController.sections as! NSFetchedResultsSectionInfo
        return sectionInfo.numberOfObjects
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let sectionInfo = fetchedResultsController.sections as! NSFetchedResultsSectionInfo
        
       let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        var info = sectionInfo.objects as! [NSManagedObject]
        let team = info[indexPath.row]
         cell.textLabel?.text = team.valueForKey("teamName") as! String
        return cell

最好可以用异步添加的方法来初始化fetchedRequest这样可以避免阻塞主线程 可以在context中使用多线程 较好的博客有 在异步线程的操作里面跟新UI

http://www.jianshu.com/p/37ab8f336f76

  var manaCtx = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
        //用异步加载的方法 个人认为更好
        asycFetch = NSAsynchronousFetchRequest(fetchRequest: fetch, completionBlock: { (result) -> Void in
        self.people = result.finalResult as! [NSManagedObject]
           
            }
            )
        do {  let a = try manaCtx.executeRequest(asycFetch!)
        }catch{
            print(error)
    }

        fetchedResultController = NSFetchedResultsController(fetchRequest: fetchReq, managedObjectContext: manaCtx, sectionNameKeyPath: nil , cacheName: nil)
        //执行加载的操作
        do { try fetchedResultController?.performFetch()
        }catch{
            print("error")
        }
        
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
           return (fetchedResultController?.sections?.count)!
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      let sectionInfo = (fetchedResultController?.sections![section])! as NSFetchedResultsSectionInfo
        return sectionInfo.numberOfObjects
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")
        var object = fetchedResultController?.objectAtIndexPath(indexPath)
        cell?.textLabel?.text = object?.valueForKey("cao")?.description
     return cell!
    }



比较好的博客

http://blog.csdn.net/yamingwu/article/details/42435083


你可能感兴趣的:(sqlite数据库的一些操作和core data的操作)