sqliteHelper
创建sqliteHelper类
/// sqlite数据库处理帮助类
///
/// 此类中封装了关于sqlite数据库处理的业务函数
class sqliteHelper
{
// 业务代码...
}
单例
private static let instance = sqliteHelper()
class var sharedInstance: sqliteHelper
{
return instance
}
var db: COpaquePointer = nil
func openDatabase(dbName: String) -> Bool
{
let path = dbName.documentPath()
println(path)
return sqlite3_open(path,&db) == sqlITE_OK
}
创建示例数据表
func createTable() -> Bool
{
let sql = "CREATE TABLE \n" +
"IF NOT EXISTS T_Department (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
"DepartmentNo CHAR(10) NOT NULL DEFAULT '',\n" +
"Name CHAR(50) NOT NULL DEFAULT '' \n" +
"); \n" +
"CREATE TABLE IF NOT EXISTS T_Employee ( \n" +
"'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + "'name' TEXT NOT NULL,\n" + "'age' INTEGER NOT NULL,\n" + "'department_id' INTEGER,\n" + "CONSTRAINT 'FK_DEP_ID' FOREIGN KEY ('department_id') REFERENCES 'T_Department' ('id') \n" + ");" // 返回结果 return execsql(sql) }
执行INSERT、UPDATE、DELETE 语句
func execsql(sql: String) -> Bool
{
return sqlite3_exec(db,sql.cStringUsingEncoding(NSUTF8StringEncoding)!,nil,nil) == ITE_OK
}
func execCount(sql: String) -> Int
{
let record = execRecordSet(sql)
return (record[0] as! [AnyObject])[0] as! Int
}
执行返回单条记录
func execRow(sql: String) -> [AnyObject]?
{
let record = execRecordSet(sql)
if record.count > 0
{
return (record[0] as! [AnyObject])
}
else
{
return nil
}
}
执行 sql 返回结果集合
func execRecordSet(sql: String) -> [AnyObject]
{
var stmt: COpaquePointer = nil
var recordList = [AnyObject]()
if sqlite3_prepare_v2(db,-1,&stmt,nil) == TE_OK
{
while sqlite3_step(stmt) == sqlITE_ROW
{
recordList.append(singleData(stmt)!)
}
}
sqlite3_finalize(stmt)
return recordList
}
执行一行数据
func singleData(stmt: COpaquePointer) -> [AnyObject]?
{
var result = [AnyObject]()
let count = sqlite3_column_count(stmt)
for index in 0..<count
{
let type = sqlite3_column_type(stmt,index)
switch type {
case sqlITE_INTEGER:
result.append(Int(sqlite3_column_int64(stmt,index)))
case sqlITE_FLOAT:
result.append(sqlite3_column_double(stmt,index))
case sqlITE_NULL:
result.append(NSNull())
case sqlITE_TEXT:
let rrrrr: UnsafePointer<UInt8> = sqlite3_column_text(stmt,index)
let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt,index))
let str = String(CString: chars,encoding: NSUTF8StringEncoding)!
result.append(str)
case let type:
println("不支持的类型 \(type)")
}
}
return result
}