代码地址:
swift 版本:点击打开链接
oc版本:点击打开链接
1.项目上需要离线操作,特此研究fmdb,并写下lyjfmdb框架。
改框架优点:
(1)一行代码实现增删改查
(2)包含事务,执行多局sql,出现问题,回滚回去
(3)讲查询到的结果自动封装成model
(4)model类创建table,model类属性支持number,int,string,float,以及PrimaryKey(自动增长),不支持的类型自动忽略
(5)查询支持全表,特定列,以及 max,min等类型
(6)表增加字段,自动执行alter表操作,不需要再从新写
文件截图如下:
2.代码:
2.1LYJFMDBShareApi
//
// LYJFMDBShareApi.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/9.
// Copyright © 2017年 hand. All rights reserved.
//
import Foundation
class LYJFMDBShareApi: NSObject {
var database:FmormDatabase?
var defaultDatabase:FmormDatabase {
get{
if database == nil {
assertionFailure("请设置基础path")
}
return database!
}
}
//单粒
private static let lYJFMDBShareApi = LYJFMDBShareApi()
class var shareApi:LYJFMDBShareApi {
return lYJFMDBShareApi
}
func initDatabaseWithPath(path:String) {
database = FmormDatabase.init(path: path)
}
}
2.2 FmormDatabase
//
// FmormDatabase.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/9.
// Copyright © 2017年 hand. All rights reserved.
//
import Foundation
import FMDB
class FmormDatabase: NSObject {
private var _debugMode = false
var lastError:Error?
var databasequeqe: FMDatabaseQueue?//队列 实现事物的的查询
private var databasepool:FMDatabasePool?//连接池
init(path:String , debugger:Bool ) {
super.init()
_debugMode = debugger
databasepool = FMDatabasePool.init(path: path)
databasequeqe = FMDatabaseQueue.init(path: path)
databasepool?.maximumNumberOfDatabasesToCreate = 3 //最大连接数
if debugger {
debugPrint("database path is \(path)")
}
}
convenience init(path:String) {
self.init(path:path ,debugger:true)
}
//MARK:设置最大连接数
func setmaxNumberdatabase(num:Int) {
databasepool?.maximumNumberOfDatabasesToCreate = UInt(num)
}
func gettablename(myclass:AnyClass) -> String {
var tableName = String.init(cString: class_getName(myclass), encoding: .utf8)
let range = tableName?.range(of: ".")?.lowerBound
tableName = tableName?.substring(from: (tableName?.index(after: range!))! )
return tableName!
}
//MARK:drop
func dropTable(myclass:AnyClass) ->Bool {
let tableName = self.gettablename(myclass: myclass)
let dropSql = "DROP TABLE \(tableName)"
return self.excute(sql: dropSql, param: nil)
}
//MARK:查询
/// <#Description#>
///
/// - Parameters:
/// - myclass: 类名
/// - others: 其他的查询入 max,min [max(id),min(id)]
/// - strWhere: <#strWhere description#>
/// - strOrderby: <#strOrderby description#>
/// - Returns: <#return value description#>
func query(myclass:AnyClass,others:Array<String>,strWhere:String?,strOrderby:String?) ->Array<Any>? {
var resultArray = Array<Any>()
let tableName = self.gettablename(myclass: myclass)
var querySql = "SELECT \(others) FROM \(tableName)"
self.checkTableExists(myclass: myclass)
if let strWhere = strWhere {
querySql.append(" WHERE \(strWhere) ")
}
if let strOrderby = strOrderby {
querySql.append(" ORDER BY \(strOrderby)")
}
if self._debugMode {
debugPrint("查询sql 是 \(querySql)")
}
let set = self.query(sql: querySql, values: [])
let propertys = TableInfo.init(myclass: myclass)._propertyMap
while set.next() {
let result = set.resultDictionary()
let obj:AnyObject = myclass.alloc() as! NSObject
for (key,value) in result! {
//String 类型 复制 nil为闪退
if !(value as AnyObject).isEqual(NSNull.init()) {
obj.setValue(value, forKey: key as! String)
}else{
let provalue = propertys?[key as! String] as! String
if provalue.contains("NSString") {
obj.setValue("", forKey: key as! String)
}else{
obj.setValue(value, forKey: key as! String)
}
}
}
resultArray.append(obj)
}
return resultArray
}
func query(myclass:AnyClass,columns:Array<String>?,strWhere:String?,strOrderby:String?) ->Array<Any>? {
var resultArray = Array<Any>()
var querySql = SqlBuilder.buildQuerySql(myclass: myclass, columns: columns)
self.checkTableExists(myclass: myclass)
if let strWhere = strWhere {
querySql.append(" WHERE \(strWhere) ")
}
if let strOrderby = strOrderby {
querySql.append(" ORDER BY \(strOrderby)")
}
if self._debugMode {
debugPrint("查询sql 是 \(querySql)")
}
let set = self.query(sql: querySql, values: [])
let propertys = TableInfo.init(myclass: myclass)._propertyMap
while set.next() {
let result = set.resultDictionary()
let obj:AnyObject = myclass.alloc() as! NSObject
for (key,value) in result! {
//String 类型 复制 nil为闪退
if !(value as AnyObject).isEqual(NSNull.init()) {
obj.setValue(value, forKey: key as! String)
}else{
let provalue = propertys?[key as! String] as! String
if provalue.contains("NSString") {
obj.setValue("", forKey: key as! String)
}else{
obj.setValue(value, forKey: key as! String)
}
}
}
resultArray.append(obj)
}
return resultArray
}
//MARK:删除
func delete(myclass:AnyClass) -> Bool {
return self.delete(myclass: myclass, strWhere: nil)
}
func delete(myclass:AnyClass,strWhere:String?) -> Bool {
var result = false
self.checkTableExists(myclass: myclass)
var deleteSql = SqlBuilder.buildDeleteSql(myclass: myclass)
if let strWhere = strWhere {
deleteSql.append(" WHERE \(strWhere)")
}
if _debugMode {
debugPrint("deleteSql is ======= \(deleteSql)")
}
result = self.excute(sql: deleteSql, param: nil)
return result
}
//MARK:更改
func update(entity:AnyObject) -> Bool {
return self.update(entity: entity, strWhere: nil)
}
func update(entity:AnyObject,strWhere:String?) -> Bool {
var result = false
self.checkTableExists(myclass: object_getClass(entity))
let info = SqlBuilder.buildUpdateSql(entity: entity)
var updateSql = info.sql
if let strWhere = strWhere {
updateSql?.append(" WHERE \(strWhere)")
}
if _debugMode {
debugPrint("updateSql is ======= \(updateSql)")
}
// result = self.excute(sql: updateSql!, param: info.arguments)
result = self.excute(sql: updateSql!, param: nil)
return result
}
//MARK:穿件索引
func createIndex(entity:AnyObject,columns:Array<String>) -> Bool {
var result = false
self.checkTableExists(myclass: object_getClass(entity))
let indexSql = SqlBuilder.buildcreateIndexSql(myclass: entity.classForCoder, columns: columns)
if _debugMode {
debugPrint("indexSql is ======= \(indexSql)")
}
// result = self.excute(sql: updateSql!, param: info.arguments)
result = self.excute(sql: indexSql, param: nil)
return result
}
//MARK:插入
func save(entity:AnyObject) -> Bool {
var result = false
self.checkTableExists(myclass: object_getClass(entity))
let info = SqlBuilder.buildInsertSql(entity: entity)
let tableInfo = info.tableInfo
if _debugMode {
debugPrint("saveSql is ======= \(info.sql)")
}
// result = self.excute(sql: info.sql!, param: info.arguments)
result = self.excute(sql: info.sql!, param: nil)
if result && tableInfo?._primaryFieldName != nil {
let lastId = self.getLastInsertRowid(tableName: (tableInfo?._myTableName)!)
entity.setValue(lastId, forKey: (tableInfo?._primaryFieldName)!)
}
return result
}
/**
* 获取刚插入的主键id,如果返回-1则是没有
*
* @param tableName
*/
func getLastInsertRowid(tableName:String) -> Int {
let querySql = "select last_insert_rowid() lastId from \(tableName)"
let reultset = self.query(sql: querySql, values: [])
var lastId = -1
if reultset.next() {
lastId = Int(reultset.int(forColumn: "lastId"))
reultset.close()
}
return lastId
}
//涉及到事务操作的多个
//MARK:判断是否存在,否则自动创建
func checkTableExists(myclass:AnyClass) ->Bool {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
if !self.isTableExist(tableInfo: tableInfo) {
let result = self.excute(sql: SqlBuilder.buildCreatTableSql(myclass: myclass), param: nil)
return result
debugPrint("查询结果\(result)")
}
return true
}
//MARK:判断是否存在
func checkTableExistsNotCreate(myclass:AnyClass) ->Bool {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
return self.isTableExist(tableInfo: tableInfo)
return true
}
func isTableExist(tableInfo:TableInfo) -> Bool{
let sql = "SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='\(tableInfo._myTableName)'"
let resultset = self.query(sql: sql, values: [])
if resultset.next() {
let count = resultset.int(forColumn: "c")
resultset.close()
if count > 0 {
return true
}else{
return false
}
} else{
return false
}
}
//MARK:dbopration
//MARK:查询
private func query(sql:String ,values:[Any]) -> FMResultSet{
var set:FMResultSet = FMResultSet()
databasepool?.inDatabase({ (db) in
let db = db!
set = db.executeQuery(sql, withArgumentsIn: values)
if db.hadError(){
self.lastError = db.lastError()
}
})
return set
}
//MARK:执行多个
func excute(sqls:Array<String>) -> Bool{
var state = false
databasequeqe!.inTransaction { (db, roollback) in
let db = db!
for sql in sqls{
state = db.executeUpdate(sql, withParameterDictionary: nil)
if !state{
break
}
}
if state {
db.commit()
}else{
self.lastError = db.lastError()
debugPrint("=====\(roollback)")
db.rollback()
}
}
return state
}
//MARK:查询之外的语句
private func excute(sql:String, param:Dictionary<String, Any>?) -> Bool{
var state = false
databasepool!.inDatabase { (db) in
let db = db!
state = db.executeUpdate(sql, withParameterDictionary: param)
if state{
db.commit()
}else{
self.lastError = db.lastError()
}
}
return state
}
}
2.3 TableInfo
//
// TableInfo.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/9.
// Copyright © 2017年 hand. All rights reserved.
//
import Foundation
class TableInfo: NSObject {
static var tableInfoMap:Dictionary<String, Any>?
var _myclass:AnyClass?
var _propertyMap:Dictionary<String, Any>?
var _myTableName:String = ""
var isTableExist:Bool = false
var _primaryFieldName:String = ""
init(myclass:AnyClass) {
super.init()
_myclass = myclass
_propertyMap = [String : Any]()
isTableExist = false
self.initTableInfo()
}
func initTableInfo() {
_myTableName = String.init(utf8String: class_getName(_myclass))!
let range = _myTableName.range(of: ".")?.lowerBound
_myTableName = _myTableName.substring(from: _myTableName.index(after: range!) )
debugPrint("tablename 是 \(_myTableName)")
// _myTableName = "TestModel"
self.buildProperty()
}
func buildProperty() {
var count: UInt32 = 0
let properties = class_copyPropertyList(_myclass, &count)
// Swift中类型是严格检查的,必须转换成同一类型
for i in 0 ..< Int(count) {
// UnsafeMutablePointer<objc_property_t>是
// 可变指针,因此properties就是类似数组一样,可以
// 通过下标获取
let property = properties?[i]
let propertyName = String.init(cString: property_getName(property), encoding: .utf8)
let attributeName = String.init(cString: property_getAttributes(property), encoding: .utf8)
if (attributeName?.contains("PrimaryKey"))! {
_primaryFieldName = propertyName!
}
_propertyMap?[propertyName!] = attributeName
}
// 不要忘记释放内存,否则C语言的指针很容易成野指针的
free(properties)
}
class func getTableInfo(myclass:AnyClass) -> TableInfo {
let className = String.init(utf8String: class_getName(myclass))!
if(tableInfoMap == nil){
tableInfoMap = Dictionary<String, Any>()
}
if tableInfoMap?[className] != nil {
return tableInfoMap![className] as! TableInfo
}
let tableInfo:TableInfo = TableInfo.init(myclass: myclass)
tableInfoMap?[className] = tableInfo
return tableInfo
}
}
2.4 主键嘞
//
// PrimaryKey.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/13.
// Copyright © 2017年 hand. All rights reserved.
//
import UIKit
/**
* 成员变量为primarykey类型,则框架自动解析为主键,自动增长
*/
class PrimaryKey: NSObject {
}
2.5 sqlBuilder
//
// SqlBuilder.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/13.
// Copyright © 2017年 hand. All rights reserved.
//
import UIKit
class SqlBuilder: NSObject {
//MARK:删除生成sql
class func buildDeleteSql(myclass:AnyClass) -> String {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
var desql = "DELETE FROM "
desql.append(tableInfo._myTableName)
return desql
}
//MARK:查询生成sql
class func buildQuerySql(myclass:AnyClass,columns:Array<String>?) -> String {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
var querySql = "SELECT "
if let columns = columns {
if columns.count>0 {
for i in 0 ..< columns.count {
querySql.append(columns[i])
querySql.append(",")
}
querySql = querySql.substrfromBegin(length: (querySql.length - 1))
}
else{
querySql.append("*")
}
}else{
querySql.append("*")
}
querySql.append(" FROM ")
querySql.append(tableInfo._myTableName)
return querySql
}
//MARK:生成索引sql
class func buildcreateIndexSql(myclass:AnyClass,columns:Array<String>) -> String {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
var indexName = tableInfo._myTableName
var indexSql = "CREATE INDEX "
var behindSql = ""
if columns.count>0 {
for i in 0 ..< columns.count {
indexName = indexName + columns[i]
behindSql.append("'\(columns[i])'")
behindSql.append(",")
}
behindSql = behindSql.substrfromBegin(length: (behindSql.length - 1))
indexSql.append(indexName)
indexSql.append(" ON \(tableInfo._myTableName) ( ")
indexSql.append(behindSql)
indexSql.append(" )")
}
return indexSql
}
//MARK: 创建表 语句 sql
class func buildCreatTableSql(myclass:AnyClass) -> String {
let tableInfo = TableInfo.getTableInfo(myclass: myclass)
var creatSql = "CREATE TABLE IF NOT EXISTS "
creatSql.append(tableInfo._myTableName)
creatSql.append("( ")
for property in tableInfo._propertyMap! {
let value = property.value as AnyObject
if value.contains("NSNumber") {
creatSql.append(property.key)
creatSql.append(" INTEGER,")
}else if value.contains("NSData"){
creatSql.append(property.key)
creatSql.append(" BLOB,")
}else if value.contains("NSString"){
creatSql.append(property.key)
creatSql.append(" TEXT,")
}else if value.contains("TB"){//bool
creatSql.append(property.key)
creatSql.append(" INTEGER,")
}else if value.contains("Tq"){//Int
creatSql.append(property.key)
creatSql.append(" INTEGER,")
}else if value.contains("Tf"){//float
creatSql.append(property.key)
creatSql.append(" REAL,")
}else if value.contains("Td"){//double
creatSql.append(property.key)
creatSql.append(" REAL,")
}else if value.contains("PrimaryKey"){
creatSql.append(property.key)
creatSql.append(" INTEGER PRIMARY KEY AUTOINCREMENT,")
}else{
//不支持的话,则忽略不创建
continue
// assertionFailure("Name for \(property.key) element type - \(value) does not support ")
}
}
creatSql = creatSql.substrfromBegin(length: (creatSql.length - 1))
creatSql.append(")")
return creatSql
}
//MARK:插入语句 sql
class func buildInsertSql(entity:AnyObject) -> SqlInfo {
let sqlInfo = SqlInfo()
let tableInfo = TableInfo.getTableInfo(myclass: object_getClass(entity))
var insertSql = "INSERT INTO "
insertSql.append(tableInfo._myTableName)
insertSql.append(" (")
let propertys = tableInfo._propertyMap!
var insertSqlbehind :String = ""
for property in propertys {
let value = property.value as AnyObject
if let entityvalue = entity.value(forKey: property.key) {
if !value.contains("PrimaryKey") {
if value.contains("NSNumber") {
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "\(entityvalue)"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("NSData"){
insertSql.append(property.key)
insertSql.append(",")
let data = entityvalue as! Data
let dataString = data.base64EncodedString(options: .endLineWithLineFeed)
let entityvalue = "'\(dataString)'"
insertSqlbehind.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
insertSqlbehind.append(",")
}else if value.contains("NSString"){
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "'\(entityvalue)'"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("TB"){//bool
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "'\(entityvalue)'"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Tq"){//Int
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "'\(entityvalue)'"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Tf"){//float
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "'\(entityvalue)'"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Td"){//double
insertSql.append(property.key)
insertSql.append(",")
let entityvalue = "'\(entityvalue)'"
insertSqlbehind.append(entityvalue)
insertSqlbehind.append(",")
sqlInfo.arguments[property.key] = entityvalue
}else{
//不支持的话,则忽略不创建
continue
// assertionFailure("Name for \(property.key) element type - \(value) does not support ")
}
}
}
}
insertSqlbehind = insertSqlbehind.substrfromBegin(length: (insertSqlbehind.length - 1))
insertSql = insertSql.substrfromBegin(length: (insertSql.length - 1))
insertSql.append(") VALUES ( ")
insertSql.append(insertSqlbehind)
insertSql.append(")")
sqlInfo.sql = insertSql
sqlInfo.tableInfo = tableInfo
return sqlInfo
}
//MARK:更新语句 sql
class func buildUpdateSql(entity:AnyObject) -> SqlInfo {
let sqlInfo = SqlInfo()
let tableInfo = TableInfo.getTableInfo(myclass: object_getClass(entity))
var updateSql = "UPDATE "
updateSql.append(tableInfo._myTableName)
updateSql.append(" SET ")
let propertys = tableInfo._propertyMap!
for property in propertys {
let value = property.value as AnyObject
if let entityvalue = entity.value(forKey: property.key) {
if !value.contains("PrimaryKey") {
if value.contains("NSNumber") {
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "\(entityvalue)"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("NSData"){
updateSql.append(property.key)
updateSql.append(" = ")
let data = entityvalue as! Data
let dataString = data.base64EncodedString(options: .endLineWithLineFeed)
let entityvalue = "'\(dataString)'"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("NSString"){
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "'\(entityvalue)'"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("TB"){//bool
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "\(entityvalue)"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Tq"){//Int
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "\(entityvalue)"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Tf"){//float
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "\(entityvalue)"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else if value.contains("Td"){//double
updateSql.append(property.key)
updateSql.append(" = ")
let entityvalue = "\(entityvalue)"
updateSql.append(entityvalue)
sqlInfo.arguments[property.key] = entityvalue
}else{
//不支持的话,则忽略不创建
continue
// assertionFailure("Name for \(property.key) element type - \(value) does not support ")
}
updateSql.append(",")
}
}
}
updateSql = updateSql.substrfromBegin(length: (updateSql.length - 1))
sqlInfo.sql = updateSql
sqlInfo.tableInfo = tableInfo
return sqlInfo
}
}
2.6 SqlInfo
//
// SqlInfo.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/13.
// Copyright © 2017年 hand. All rights reserved.
//
import UIKit
class SqlInfo: NSObject {
var arguments : Dictionary<String,Any> = Dictionary()
var sql:String?
var tableInfo:TableInfo?
}
2.7 扩展类
//
// NSObject+Extension.swift
// MyswiftDemo
//
// Created by Liyanjun on 2017/2/14.
// Copyright © 2017年 hand. All rights reserved.
//
import UIKit
extension NSObject {
//MARK:创建表
func creatTable() ->Bool {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.checkTableExists(myclass: self.classForCoder) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
//MARK:创建索引
func createIndex(columns:Array<String>) -> Bool {
if columns.count <= 0 {
debugPrint("错误代码==请输入列名")
return false
}else{
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.createIndex(entity: self, columns: columns) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
}
//MARK:插入
func insertIntosqlite() ->Bool {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.save(entity: self) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
//MARK:DROP
func dropTable()-> Bool {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.dropTable(myclass: self.classForCoder) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
//MARK:update
func updateWithWhereStr(whereStr:String?) -> Bool {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.update(entity: self, strWhere: whereStr) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
//MARK:delete
func deleteWithWhereStr(whereStr:String?) -> Bool {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
if fmormDatabase.delete(myclass: self.classForCoder, strWhere: whereStr) {
return true
} else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return false
}
}
//MARK:查询
//MARK:查询 max,min等的查询
func query(others:Array<String>,strWhere:String?,strOrderby:String?) ->Array<Any>? {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
let array = fmormDatabase.query(myclass: self.classForCoder, others: others, strWhere: strWhere, strOrderby: strOrderby)
if array != nil {
return array
}else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return nil
}
}
func queryWithWhereStr(columns:Array<String>?,whereStr:String?,orderBy:String?) -> Array<Any>? {
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
let array = fmormDatabase.query(myclass: self.classForCoder, columns: columns, strWhere: whereStr, strOrderby: orderBy)
if array != nil {
return array
}else{
debugPrint("错误代码==\(fmormDatabase.lastError?.localizedDescription)")
return nil
}
}
func queryWithWhereStr(whereStr:String?,orderBy:String?) -> Array<Any>? {
return self.queryWithWhereStr(columns: nil, whereStr: whereStr, orderBy: orderBy)
}
}
3.使用案例:
3.1 创建数据库 最好写在 AppDelegate中
func pathForDocumentsResourc(relativePath:String) -> String {
var documentsPath:String = ""
if documentsPath == "" {
let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
documentsPath = documentPaths[0]
}
return documentsPath.appending("/\(relativePath)")
}
func initaFmdabase() {
LYJFMDBShareApi.shareApi.initDatabaseWithPath(path: self.pathForDocumentsResourc(relativePath: "MyswiftDemo.db") )
}
3.2 创建表,创建索引,插入表
let fmormDatabase = LYJFMDBShareApi.shareApi.defaultDatabase
var sqls = Array<String>()
var i = 0
//空间列表
for spaceList in spaces {
let spaceList = spaceList as SpaceList
spaceList.fmdbownerid = global.ownerid
if i == 0 {
if !spaceList.creatTable(){
self.displayAlertControllerWithMessage("创建表失败")
return
}else{
//1.删除表
spaceList.deleteWithWhereStr(whereStr: nil)
//2.创建索引
spaceList.createIndex(columns: ["fmdbownerid"])
}
}
let sql = SqlBuilder.buildInsertSql(entity: spaceList).sql
sqls.append(sql!)
i += 1
}
if fmormDatabase.excute(sqls: sqls) {
self.redirectToMainScene()
}else{
debugPrint("错误信息是==\(fmormDatabase.lastError?.localizedDescription)")
self.displayAlertControllerWithMessage("同步本地失败")
}
3.3 查询
(1)全表
let spaceListfmdb = SpaceList()
self.spaceList = spaceListfmdb.queryWithWhereStr(whereStr: "fmdbownerid = '\(global.ownerid)'", orderBy: nil) as! [SpaceList]
self.tableView.reloadData()
(2)特定列
let spaceListfmdb = SpaceList()
self.spaceList = spaceListfmdb.queryWithWhereStr(columns: ["'id','id2'"], whereStr: " 1=1 ", orderBy: <#T##String?#>) as! [SpaceList]
self.tableView.reloadData()
(3)其他
let spaceListfmdb = SpaceList()
self.spaceList = spaceListfmdb.self.testmodel.query(others: "max(id)", strWhere: <#T##String?#>, strOrderby: <#T##String?#>) as! [SpaceList]
self.tableView.reloadData()