最近项目中使用到了sqlite.swift,其中的一些方法做一下记录,github上面有的就不做赘述了。
/**
根据字段和主键创建表
*/
let primaryKey//主键
let keys//所以的列
do {
try db?.run(users.create(ifNotExists: true, block:{ (t) in
for key in keys {
let sqlite_key = Expression<String?>(key)
if key == primaryKey {
let primaryKeyExpression = Expression<String>(key)
t.column(primaryKeyExpression, primaryKey: true)
}else {
t.column(sqlite_key)
}
}
}))
} catch {
}
/**
判断表是否存在
*/
let tname //表名
let sqliteMaster = Table("sqlite_master")
let type = Expression<String>("type")
let name = Expression<String>("name")
do {
let tableCount = try db!.scalar(sqliteMaster.filter(type == "table" && name == tname).count)
return tableCount == 1
} catch {
return false
}
/**
更新列,当某一列不存在时,添加该列
*/
let name//表名
let Keys//所以字段名
do {
let users = Table(name)
let expression = users.expression
let columnNames = try db!.prepare(expression.template, expression.bindings).columnNames
for key in Keys {
var isExist = false
for columnName in columnNames {
if key == columnName {
isExist = true
break
}
}
if !isExist {
do {
try db!.run(users.addColumn(Expression<String?>(key)))
} catch {
}
}
}
} catch {
}
以上只列出了部分,其余的增删改查请上github查看。第一次写博客,如有错误的地方请指正,谢谢。