Thursday, 21 December 2017

SQLite Demo

step 1: Add following libraries.
1. libsqlite3.tbd
2. libsqlite3.0.tbd

step 2: Create Bridgeheader.h (Header) file.

step 3: Import sqlite3. Like,


#import <sqlite3.h>

step 4: Create database and table using "DB Browser For SQLite".
step 5: After create database and table, drag database_name.sqlite file and drop on your project.
step 6: Put the following code on AppDelegate. Like,

var window: UIWindow?
    var db : OpaquePointer? = nil
    
    internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
    internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

step 7: Create the copy_file function. Like,

func copy_file() {
        let file_manager = FileManager.default
        let document_path = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let destination_sqlite_url = document_path.appendingPathComponent("kaumil_db.sqlite")
        let source_sqlite_url = Bundle.main.url(forResource: "kaumil_db", withExtension: "sqlite")
        
        print("\(destination_sqlite_url.path)")
        
        if !file_manager.fileExists(atPath: destination_sqlite_url.path)
        {
            do
            {
                try file_manager.copyItem(at: source_sqlite_url!, to: destination_sqlite_url)
                print("copied..")
                print(destination_sqlite_url.path)
            }
            catch let error as NSError
            {
                print("Enable to create database:\(error.debugDescription)")
            }
        }
        if sqlite3_open(destination_sqlite_url.path, &db) != SQLITE_OK
        {
            print("Error open database..")
        }
        else
        {
            print("Success open database..")
        }
    }

step 8: Call the copy function in DidFinishingLaunchingWithOptions method on AppDelegate. Like,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        copy_file()
        
        // Override point for customization after application launch.
        return true
    }

step 9: Create select query function(Get data from table). Like,

func get_data_from_table(_ querySQL : String) -> NSMutableArray {
        var statement : OpaquePointer? = nil
        
        if sqlite3_prepare_v2(db, querySQL, -1, &statement, nil) != SQLITE_OK
        {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("Error prepaer select:\(error_msg)")
        }
        
        let arr_of_Users : NSMutableArray = NSMutableArray()
        while sqlite3_step(statement) == SQLITE_ROW {
            
            
            let login_id = sqlite3_column_text(statement, 0)
            var login_id_str = String()
            if login_id != nil
            {
                login_id_str = String(cString: login_id!)
                print("Login id is=\(login_id_str)")
            }
            else
            {
                print("Login id is not found")
            }
            
            let login_pass = sqlite3_column_text(statement, 1)
            var login_pass_str = String()
            if login_pass != nil
            {
                login_pass_str = String(cString: login_pass!)
                print("Login password is=\(login_pass)")
            }
            else
            {
                print("Login password is not found")
            }
            
            let dict_of_user : NSMutableDictionary = NSMutableDictionary()
            dict_of_user.setObject(login_id_str, forKey: "login_id" as NSCopying)
            dict_of_user.setObject(login_pass_str, forKey: "login_pass" as NSCopying)
            
            arr_of_Users.add(dict_of_user)
        }
        print(arr_of_Users)
        
        if sqlite3_finalize(statement) != SQLITE_OK
        {
            let err_msg = String(cString: sqlite3_errmsg(db))
            print("Error finalized prepared statement\(err_msg)")
        }
        statement = nil
        return arr_of_Users
    }

step 10: Insert Data in table, put following code. Like,

func insert_data(_ queryStr : String) {
        var statement : OpaquePointer? = nil
        if sqlite3_prepare_v2(db, queryStr, -1, &statement, nil) != SQLITE_OK {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("error preparing insert\(error_msg)")
        }
        if sqlite3_step(statement) != SQLITE_DONE {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("failure inserting foo\(error_msg)")
        }
        else
        {
            print("successfully inserted..")
        }
    }

step 11: For get data from table and insert the data in table put following code in                                                DidFinishLaunchingWithOptions method. Like,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        copy_file()
        
        let dict : NSMutableDictionary = NSMutableDictionary()
        
        dict.setObject("student_202", forKey: "login_id" as NSCopying)
        dict.setObject("stud_345", forKey: "login_pass" as NSCopying)
        
        let string_data = "insert into login (login_id,login_pass) values ('\(dict.value(forKey: "login_id")!)','\(dict.value(forKey: "login_pass")!)')"
        
        insert_data(string_data)
        get_data_from_table("select * from login")
        // Override point for customization after application launch.
        return true
    }

step 12: For update data from database, create following function. Like,


//Mark:- Update data in database...
    func update_data(_ queryStr : String) {
        var statement : OpaquePointer? = nil
        
        if sqlite3_prepare_v2(db, queryStr, -1, &statement, nil) != SQLITE_OK
        {
            let errMessage = String(cString: sqlite3_errmsg(db))
            print("Failure Updating Foo: \(errMessage)")
        }
        if sqlite3_step(statement) != SQLITE_DONE
        {
            let errMessage = String(cString: sqlite3_errmsg(db))
            print("Failure Updating Foo: \(errMessage)")
        }
        else
        {
            print("Successfully Updated")
        }

    }

step 13: Call the function in DidFinishLaunchingWithOptions. Like,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        copy_file()
        
        let dict : NSMutableDictionary = NSMutableDictionary()
        
        dict.setObject("student_202", forKey: "login_id" as NSCopying)
        dict.setObject("stud_345", forKey: "login_pass" as NSCopying)
        
        let string_data = "insert into login (login_id,login_pass) values ('\(dict.value(forKey: "login_id")!)','\(dict.value(forKey: "login_pass")!)')"
        
        insert_data(string_data)
        
        let update_str = "UPDATE login set login_pass='kaumil_bhatt' WHERE login_id = 'student_202'"
        
        update_data(update_str)
        get_data_from_table("select * from login")
        // Override point for customization after application launch.
        return true

    }

step 14: For delete data from database, create this function. Like,

func delete_data(_ queryStr : String) {
        var statement : OpaquePointer? = nil
        
        if sqlite3_prepare_v2(db, queryStr, -1, &statement, nil) != SQLITE_OK
        {
            let errMessage = String(cString: sqlite3_errmsg(db))
            print("Failure Deleting Foo: \(errMessage)")
        }
        if sqlite3_step(statement) != SQLITE_DONE
        {
            let errMessage = String(cString: sqlite3_errmsg(db))
            print("Failure Deleting Foo: \(errMessage)")
        }
        else
        {
            print("Successfully Deleted")
        }

    }

step 15: Call this function on DidFinishLaunchingWithOption. Like,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        copy_file()
        
        let dict : NSMutableDictionary = NSMutableDictionary()
        
        dict.setObject("student_202", forKey: "login_id" as NSCopying)
        dict.setObject("stud_345", forKey: "login_pass" as NSCopying)
        
        let string_data = "insert into login (login_id,login_pass) values ('\(dict.value(forKey: "login_id")!)','\(dict.value(forKey: "login_pass")!)')"
        
        insert_data(string_data)
        
        let delete_str = "delete from login WHERE login_id = 'student_202'"
        
        delete_data(delete_str)
        get_data_from_table("select * from login")
        // Override point for customization after application launch.
        return true
    }

Thank You...

No comments:

Post a Comment