--- Using SQLite in Swift, --- swiftsqlite

Source: Internet
Author: User

--- Using SQLite in Swift, --- swiftsqlite

SQLite. swift is an operating framework that uses the pure Swift language to encapsulate SQLite3.

Features:

  • Simple query and parameter binding Interfaces

  • Secure and Automatic Data Access

  • Implicit commit and rollback APIs

  • Developer-friendly error handling and debugging

  • Comprehensive documentation

  • Passed extensive tests

DEMO code:

Import Foundation/** 1. open Database 2. if no data table exists, create table 3 first. data operation */class SQLite {var db: COpaquePointer = nil // open the database //: param: dbname database name ////: returns: func openDatabase (dbname: String) Enabled) -> Bool {// UnsafePointer <Int8> UnsafePointer <CChar> // the char in the C language * // the filename must be the complete path name. let path = dbname.doc umentPath () println (path) // sqlite3_open if the database does not exist, a new database file will be created. // if the database file already exists, open it directly and return a handle, It does not affect the data. if sqlite3_open (path, & db) = SQLITE_ OK {println ("") // In essence, you only need to run it once. if createTable () {println ("") // TODO: test the data query. let SQL = "SELECT id, DepartmentNo, Name FROM T_Department;" recordSet (SQL )} else {println ("failed to create a table")} else {println ("failed to open the Database")} return false} // create a data table and set the data table required by the system, one-time creation of private func createTable ()-> Bool {// prepare SQL statements for all data tables // 1> after each SQL statement is completed, a private func createTable () Write SQL statements in an invasive table together, add a \ n 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 )} /// execute the SQL statement that does not return a value /////: param: SQL SQL String /////: returns: whether func execSQL is successful (SQL: String) -> Bool {/** 1. database pointer 2. SQL string C Format 3. callback: The function callback after the SQL command is executed, usually nil 4. pointer of the first parameter of the callback 5. error message, which is usually passed into nil */return sqlite3_exec (db, SQL. cStr IngUsingEncoding (NSUTF8StringEncoding )!, Nil, nil, nil) = SQLITE_ OK} // run the SQL statement to return a result set (Object array) //: param: SQL SQL string func recordSet (SQL: string) {// 1. prepare the statement var stmt: COpaquePointer = nil/** 1. database handle 2. SQL C string 3. the string length of the SQL C language is strlen,-1 is automatically calculated 4. stmt pointer 5. generally, nil */if sqlite3_prepare_v2 (db, SQL. cStringUsingEncoding (NSUTF8StringEncoding )!, -1, & stmt, nil) = SQLITE_ OK {// obtain the SQL Execution result in one step-> sqlite3_setup corresponds to a record while sqlite3_step (stmt) = SQLITE_ROW {// obtain the data recordData (stmt) of each record }}/// obtain the record of each record //: param: stmt prepared_statement object func recordData (stmt: COpaquePointer) {// retrieve record var count = sqlite3_column_count (stmt) println ("retrieve record, total number of columns \ (count )") // traverse the data in each column for I in 0 .. <count {let type = sqlite3_column_type (stmt, I) // Extract the switch type {case SQLITE_INTEGER: println ("integer \ (sqlite3_column_int64 (stmt, I)") case SQLITE_FLOAT Based on the field type: println (" \ (sqlite3_column_double (stmt, I)") case SQLITE_NULL: println ("null \ (NSNull ()") case SQLITE_TEXT: let chars = UnsafePointer <CChar> (sqlite3_column_text (stmt, I) let str = String (CString: chars, encoding: NSUTF8StringEncoding )! Println ("string \ (str)") case let type: println ("unsupported type \ (type )")}}}}

 

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.