ios swift sqlite3 简单使用

一.创建Person类

Swift 复制代码
import UIKit

class Person: NSObject {
    
    var name:String? = nil
    var sex:String? = nil
    var age:String? = nil
        
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }

}

二.在使用的地方导入sqlite.3头文件,例如方法都在viewcontroller中使用

Swift 复制代码
import UIKit
import SQLite3

三.viewcontroller数据sqlite的增,删,查,等方法

Swift 复制代码
    //打开数据库表
    func opneDB() -> Bool {
        let docDir:String! = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        let fileName:String! = docDir + "/demo1.sqlite"
        if sqlite3_open(fileName, &db) != SQLITE_OK {
            print("打开数据库失败")
            return false
        } else {
            print("打开数据库成功")
            return true
        }
    }

    //创建数据库表
    func creatTable() ->Bool {
        let sql = "CREATE TABLE persontable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT NOT NULL, age TEXT NOT NULL,sex TEXT NOT NULL);"
            // 第1个参数是 数据库db 第2个是要执行的sql 第3,4个是回调  第5个是错误信息
            let result = sqlite3_exec(db, sql, nil, nil, nil)
            return result == SQLITE_OK
    }
    
    
    // 插入数据
    func insert(nameText:String, ageText:String, sexText:String) -> Bool{
        let sql = "insert into persontable(name,age,sex) VALUES(?,?,?);"
        var stmt: OpaquePointer?
        let prepareResult = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
        if prepareResult != SQLITE_OK {
          sqlite3_finalize(stmt)
          if let msg = sqlite3_errmsg(db) {
            print("insert prepare 发生错误: \(msg)")
          }
          return false
        }
        let name = (nameText as NSString).utf8String
        let age = (ageText as NSString).utf8String
        let sex = (sexText as NSString).utf8String
        sqlite3_bind_text(stmt, 1, name, -1, nil)
        sqlite3_bind_text(stmt, 2, age, -1, nil)
        sqlite3_bind_text(stmt, 3, sex, -1, nil)
        let stepResult = sqlite3_step(stmt)

        if stepResult != SQLITE_OK && stepResult != SQLITE_DONE {
          sqlite3_finalize(stmt)
          if let msg = sqlite3_errmsg(db) {
            print("insert step 发生错误: \(msg)")
          }
          return false
        }
        sqlite3_finalize(stmt)
        return true
      }
    
    
    // 查询数据
    func queryAll()-> [Any]? {
        var persons = [Person]()
        //根据查询条件查询数据
        //let namestr:String = "张三"
        //let sql = "SELECT * FROM persontable WHERE  name LIKE '%\(namestr)%';"
        let sql = "SELECT * FROM persontable ;"
        var stmt: OpaquePointer?
        // 编译
        let prepareResult = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
        if prepareResult != SQLITE_OK {
          // 关闭语句句柄
          sqlite3_finalize(stmt)
          if let msg = sqlite3_errmsg(db) {
            print("insert prepare 发生错误: \(msg)")
          }
          return []
        }

        while sqlite3_step(stmt) == SQLITE_ROW {
            let person = Person()
            //let index = String.init(cString: sqlite3_column_text(stmt, 0)!)
            let name = String.init(cString: sqlite3_column_text(stmt, 1)!)
            let age = String.init(cString: sqlite3_column_text(stmt, 2)!)
            let sex = String.init(cString: sqlite3_column_text(stmt, 3)!)
            print("查询数据----\(name)--\(age)--\(sex)")
            person.name = name
            person.age = age
            person.sex = sex
            persons.append(person)
        }
        sqlite3_finalize(stmt)
        print("查询数据库成功")
        return persons
      }
    
    //更新列表
    func update(name: String, toName: String) -> Bool {
        //根据条件删除
      let sql = "update persontable set tradename = '\(toName)' where tradename = '\(name)'";
      return self.exec(sql: sql)
    }
    // 删除数据
    func delete(name: String) -> Bool{
      //删除sql语句
      //let sql = "delete from qingmeitable where tradename = '\(name)'"
      let sql = "delete from persontable "
      return self.exec(sql: sql)
    }
    
    // 执行编译sql
    private func exec(sql: String) -> Bool{
      // sqlite3_stmt指针
      var stmt: OpaquePointer?
      // 编译
      let prepareResult = sqlite3_prepare_v2(self.db, sql, -1, &stmt, nil)
      if prepareResult != SQLITE_OK {
        // 关闭语句句柄
        sqlite3_finalize(stmt)
        if let msg = sqlite3_errmsg(db) {
          print("delete prepare 发生错误: \(msg)")
        }
        return false
      }
      let stepResult = sqlite3_step(stmt)
      if stepResult != SQLITE_OK && stepResult != SQLITE_DONE {
        sqlite3_finalize(stmt)
        if let msg = sqlite3_errmsg(db) {
          print("delete step 发生错误: \(msg)")
        }
        return false
      }
      sqlite3_finalize(stmt)
      return true
    }

参考链接

相关推荐
Wx-bishekaifayuan1 小时前
django电商易购系统-计算机设计毕业源码61059
java·spring boot·spring·spring cloud·django·sqlite·guava
CopyDragon5 小时前
设置域名跨越访问
数据库·sqlite
云空6 小时前
《Python 与 SQLite:强大的数据库组合》
数据库·python·sqlite
DisonTangor9 小时前
苹果发布iOS 18.2首个公测版:Siri接入ChatGPT、iPhone 16拍照按钮有用了
ios·chatgpt·iphone
- 羊羊不超越 -9 小时前
App渠道来源追踪方案全面分析(iOS/Android/鸿蒙)
android·ios·harmonyos
极客小张10 小时前
基于STM32的智能充电桩:集成RTOS、MQTT与SQLite的先进管理系统设计思路
stm32·单片机·嵌入式硬件·mqtt·sqlite·毕业设计·智能充电桩
YUJIANYUE15 小时前
PHP将指定文件夹下多csv文件[即多表]导入到sqlite单文件
jvm·sqlite·php
2401_865854881 天前
iOS应用想要下载到手机上只能苹果签名吗?
后端·ios·iphone
Bonne journée1 天前
SQLite数据库是什么?DB Browser for SQLite是什么?
数据库·sqlite
HackerTom2 天前
iOS用rime且导入自制输入方案
ios·iphone·rime