The swift version of the SQLite help class

Source: Internet
Author: User
Tags sqlite stmt

Sqlitehelper Creating the Sqlitehelper class
///  SQLite数据库处理帮助类//////  此类中封装了关于SQLite数据库处理的业务函数class SQLiteHelper{    // 业务代码...}
Single case
privatestaticlet instance = SQLiteHelper()/// 单例  全局的数据访问接口var sharedInstance: SQLiteHelper{    return instance}
Global variables
varnil
Open Database
///  打开数据库//////  :param: dbName 数据库名称//////  :returns: 返回 是否打开成功func openDatabase(dbName: String) -> Bool{    let path = dbName.documentPath()    println(path)    return sqlite3_open(path, &db) == SQLITE_OK}
To create a sample data table
///create t_department and T_employee tables//// /: Returns: Returns whether the creation was successfulFunc createtable ()-bool{Let sql ="CREATE TABLE \ n"+"IF not EXISTS t_department (\ n"+"id INTEGER PRIMARY KEY autoincrement not null,\n"+"Departmentno CHAR (Ten) not NULL DEFAULT ', \ n"+"Name CHAR () 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" +    ");"//Returns the result return Execsql (SQL)}
Execute INSERT, UPDATE, DELETE statement
///  执行INSERT、UPDATE、DELETE SQL语句//////  :param: sql SQL语句//////  :returns: 返回 是否执行成功func execSql(sql: String) -> Bool{    // 返回结果   return sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == ITE_OK}
Execute SQL statement returns number of results
///  执行SQL语句 返回结果数量//////  :param: sql SQL语句//////  :returns: 返回 结果func execCount(sql: String) -> Int{    let record = execRecordSet(sql)    // 返回结果    return (record[0as! [AnyObject])[0as! Int}
Execution returns a single record
///  执行返回单条记录//////  :param: sql SQL语句//////  :returns: 返回 单条记录func execRow(sql: String) -> [AnyObject]?{    let record = execRecordSet(sql)    if0    {        return (record[0as! [AnyObject])    }    else    {        return nil    }}
Execute SQL return result collection
///   execute SQL return result collection//////   :p aram:sql SQL statements////   /: Returns: Returns the result set of the queryFunc Execrecordset (sql:string), [anyobject]{varStmt:copaquepointer = NilvarRecordlist = [Anyobject] ()ifSQLITE3_PREPARE_V2 (DB, Sql.cstringusingencoding (nsutf8stringencoding)!,-1, &stmt, nil) = = TE_OK { whileSqlite3_step (stmt) = = Sqlite_row {recordlist.append (Singledata (stmt)!) }    }//Release statementSqlite3_finalize (stmt)//Return results    returnRecordlist}
Execute a row of data
///   execute a row of data//////   :p statements executed by aram:stmt////   //: Returns: Returns a row of data arraysFunc Singledata (Stmt:copaquepointer), [Anyobject]? {varresult = [Anyobject] ()//Returns the number of columns in the table     LetCount = Sqlite3_column_count (stmt)//#define Sqlite_integer 1    //#define SQLITE_FLOAT 2    //#define SQLITE_BLOB 4    //#define SQLITE_NULL 5    //#ifdef Sqlite_text    //# undef Sqlite_text    //#else    //# define Sqlite_text 3    //#endif    //#define SQLITE3_TEXT 3     forIndexinch 0.. <count { LetType = Sqlite3_column_type (stmt, index)//Based on the type of the field, extract the value of the corresponding column        SwitchType { CaseSQLITE_INTEGER:result.append (Int (Sqlite3_column_int64 (stmt, index))) CaseSQLITE_FLOAT:result.append (sqlite3_column_double (stmt, index)) CaseSQLITE_NULL:result.append (NSNull ()) CaseSqlite_text: Letrrrrr:unsafepointer<uint8> = Sqlite3_column_text (stmt, index) Letchars = unsafepointer<cchar> (Sqlite3_column_text (stmt, index)) Letstr = String (cstring:chars, encoding:nsutf8stringencoding)! Result.append (str) Case  LetType:println ("Unsupported type \ (type)")        }    }//Return results    returnResult

The swift version of the SQLite help class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.