The use of SQLite in pure Swift

Source: Internet
Author: User
Tags prepare sqlite stmt

Sqlite.swift is an operating framework that encapsulates SQLite3 using the pure Swift language.

Characteristics:

    • Simple query and parameter binding interface

    • Secure, automated type of data access

    • Implicit commit and rollback interfaces

    • Developer-friendly error handling and debugging

    • Document Perfection

    • Through extensive testing

Demo Code:

Import Foundation/** 1. Open Database 2. If there is no data table, you need to first create table 3. Data Manipulation*/classSQLite {var db:copaquepointer=Nil///Open Database///    ///:p aram:dbname Database name///    ///: Returns: Whether to open successfullyFunc OpenDatabase (dbname:string)Bool {//unsafepointer<int8> unsafepointer<cchar>//corresponding to char* in C language//filename must be the full path nameLet path =Dbname.documentpath () println (path)//Sqlite3_open If the database does not exist, a new database file is created//if the database file already exists, open it directly and return the handle without any effect on the data        ifSqlite3_open (path, &db) = =SQLITE_OK {println ("Open Database succeeded")                        //essentially, it only needs to be run once.            ifcreatetable () {println ("success in the creation of a table")                                //TODO: Test query dataLet sql ="SELECT ID, Departmentno, Name from T_department;"recordSet (SQL)}Else{println ("failed to create a table")            }        } Else{println ("failed to open database")        }                return false    }        ///Create a data table, create a data table that the system needs, once    PrivateFunc createtable ()Bool {//prepare SQL for all data tables//1> Each SQL is completed with one; //2> Write all the Genesis SQL together, adding a \ n for each line breakLet 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 (a) 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 is not NULL, \ n"+"' department_id ' INTEGER, \ n"+"CONSTRAINT ' fk_dep_id ' FOREIGN KEY (' department_id ') REFERENCES ' t_department ' (' ID ') \ n"+");"                returnexecsql (SQL)}///Execute SQL statement with no return value///    ///:p aram:sql SQL string///    ///: Returns: whether successfulFunc Execsql (sql:string)Bool {/** 1. Database pointer 2. SQL string in C language format 3. Callback, which executes a function callback after the completion of the SQL instruction, usually nil 4. Pointer to the first parameter of the callback 5. Error messages, which are also usually passed to nil*/        returnSqlite3_exec (DB, sql.cstringusingencoding (nsutf8stringencoding)!, nil, nil, nil) = =SQLITE_OK}///Execute SQL Returns a result set (object array)///    ///:p aram:sql SQL stringfunc RecordSet (sql:string) {//1. Prepare the statementvar stmt:copaquepointer =Nil/** 1. Database handle 2. The C language of SQL string 3. The string length of the C language of SQL strlen,-1 automatically calculates 4. STMT's Pointer 5. Usually pass in nil*/        ifSQLITE3_PREPARE_V2 (DB, Sql.cstringusingencoding (nsutf8stringencoding)!,-1, &stmt, nil) = =SQLITE_OK {//single-Step Get SQL Execution results-Sqlite3_setup corresponds to a record             whileSqlite3_step (stmt) = =Sqlite_row {//get the data for each recordrecorddata (stmt)}} }        ///get a record of each piece of data///    ///:p aram:stmt prepared_statement Objectsfunc RecordData (stmt:copaquepointer) {//get to recordvar count =Sqlite3_column_count (stmt) println ("get to record, total number of columns \ (count)")        //traverse data for each column         forIinch 0.. <count {Let type=Sqlite3_column_type (stmt, i)//extracts the value of the corresponding column based on the type of the field            Switchtype { CaseSqlite_integer:println ("integer \ (sqlite3_column_int64 (stmt, i))")             CaseSqlite_float:println ("small tree \ (sqlite3_column_double (stmt, i))")             CaseSqlite_null:println ("empty \ (NSNull ())")             CaseSqlite_text:let chars= unsafepointer<cchar>(Sqlite3_column_text (stmt, i)) let str= String (Cstring:chars, encoding:nsutf8stringencoding)!println ("string \ (str)")             CaseLet type:println ("Unsupported type \ (type)")            }        }    }}

The use of SQLite in pure Swift

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.