How Many Way Are There to Do Crud Operation in Sqlite Swift

How many way are there to do CRUD operation in SQLite Swift?

I think GRDB is the right way to do this.
GRDB is faster than FMDB and SQLite.swift also
really easy to fetch data
Refer this link - https://github.com/groue/GRDB.swift

Accessing an SQLite Database in Swift

While you should probably use one of the many SQLite wrappers, if you wanted to know how to call the SQLite library yourself, you would:

  1. Configure your Swift project to handle SQLite C calls. If using Xcode 9 or later, you can simply do:

    import SQLite3
  2. Create/open database.

    let fileURL = try! FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("test.sqlite")

    // open database

    var db: OpaquePointer?
    guard sqlite3_open(fileURL.path, &db) == SQLITE_OK else {
    print("error opening database")
    sqlite3_close(db)
    db = nil
    return
    }

    Note, I know it seems weird to close the database upon failure to open, but the sqlite3_open documentation makes it explicit that we must do so to avoid leaking memory:

    Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.

  3. Use sqlite3_exec to perform SQL (e.g. create table).

    if sqlite3_exec(db, "create table if not exists test (id integer primary key autoincrement, name text)", nil, nil, nil) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error creating table: \(errmsg)")
    }
  4. Use sqlite3_prepare_v2 to prepare SQL with ? placeholder to which we'll bind value.

    var statement: OpaquePointer?

    if sqlite3_prepare_v2(db, "insert into test (name) values (?)", -1, &statement, nil) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error preparing insert: \(errmsg)")
    }

    if sqlite3_bind_text(statement, 1, "foo", -1, SQLITE_TRANSIENT) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("failure binding foo: \(errmsg)")
    }

    if sqlite3_step(statement) != SQLITE_DONE {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("failure inserting foo: \(errmsg)")
    }

    Note, that uses the SQLITE_TRANSIENT constant which can be implemented as follows:

    internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
    internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
  5. Reset SQL to insert another value. In this example, I'll insert a NULL value:

    if sqlite3_reset(statement) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error resetting prepared statement: \(errmsg)")
    }

    if sqlite3_bind_null(statement, 1) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("failure binding null: \(errmsg)")
    }

    if sqlite3_step(statement) != SQLITE_DONE {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("failure inserting null: \(errmsg)")
    }
  6. Finalize prepared statement to recover memory associated with that prepared statement:

    if sqlite3_finalize(statement) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error finalizing prepared statement: \(errmsg)")
    }

    statement = nil
  7. Prepare new statement for selecting values from table and loop through retrieving the values:

    if sqlite3_prepare_v2(db, "select id, name from test", -1, &statement, nil) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error preparing select: \(errmsg)")
    }

    while sqlite3_step(statement) == SQLITE_ROW {
    let id = sqlite3_column_int64(statement, 0)
    print("id = \(id); ", terminator: "")

    if let cString = sqlite3_column_text(statement, 1) {
    let name = String(cString: cString)
    print("name = \(name)")
    } else {
    print("name not found")
    }
    }

    if sqlite3_finalize(statement) != SQLITE_OK {
    let errmsg = String(cString: sqlite3_errmsg(db)!)
    print("error finalizing prepared statement: \(errmsg)")
    }

    statement = nil
  8. Close database:

    if sqlite3_close(db) != SQLITE_OK {
    print("error closing database")
    }

    db = nil

For Swift 2 and older versions of Xcode, see previous revisions of this answer.

Storing/ Accessing Large Amounts of Data in Swift

Create a Sqlite db from your excel and create specific query for your needs. I recommend using FMDB for this, its written in Objective-C but there is a description for how to use it in Swift

EDIT:As Gwendal Roué mentioned there is a better alternative using GRDB instead of FMDB

Is there a proper way to make generic crud functions for Core Data in Swift?

The issue is, that users and movies are saved in their respected tables, but I want to have user's ID in the foreign key of movies as well.

The first thing you need to do is to stop thinking of Core Data as if it were a SQL database. It's not designed to work the same way, and trying to use it like SQL will make things difficult for you. Core Data uses SQLite internally, but its API is not SQL-like.

You don't use foreign keys in Core Data, you use relationships. You already have the relationship you need, so that's what you would normally use with Core Data. If you have a Movies instance and you want to know what User goes with that movie, you use the user relationship that you already have. To make that work, you need to assign a value for the relationship when you create an instance. When you create a Movies, assign a value to the user relationship. A foreign key isn't necessary, because the relationship exists.

If you prefer to use a SQL-like approach, there are several open source SQLite wrappers available, for example FMDB and PLDatabase.

How to delete records in SQLite in iOS Application

Your query string appears to be using double quotes instead of single quotes:

NSString *querySQL = [NSString
stringWithFormat: @"delete from TRACK_IT where TRACKING_NUMBER=\"%@\"",trkNum];
// ^ ^
// | |
// Here and Here

Replacing with single quotes should fix this syntax error:

NSString *querySQL = [NSString
stringWithFormat: @"delete from TRACK_IT where TRACKING_NUMBER='%@'",trkNum];

However, unless trkNum is built into your own program, do not use this method of deleting records: if the data comes from the user, you open your app to SQL injection attacks.

how to make database in sqlite through wizard in xcode and how to connect with database?

What you are looking for is called Core Data. It will be impossible to describe how to set it up in one short post. Here is the link to a nice tutorial that should give you the basics. Essentially, Core Data is an object graph that is hard to understand right away but is an extremely powerful tool and one of the perks in iOS Development.

Saving data into sqlite3 database in Swift

A few observations:

  1. With sqlite3_bind_blob, the fourth parameter is the size, which is required, and must not be negative. With sqlite3_bind_text, you can supply a -1 value because C strings are null terminated and it can figure out where the string ends, but it can’t do that with a blob.

    As the documentation says:

    If the fourth parameter to sqlite3_bind_blob() is negative, then the behavior is undefined.

    Thus, perhaps:

    guard let blob = drawingBuffer.baseAddress else { return }
    let count = Int32(drawingBuffer.count)

    And then:

    sqlite3_bind_blob(statement, 1, blob, count, nil)
  2. Also, if a SQLite call fails, you should print the error, otherwise you are flying blind, e.g.

    let errorMessage = sqlite3_errmsg(database).map { String(cString: $0) } ?? "Unknown error"
    print("failure preparing UPDATE statement: \(errorMessage)")

    You should do that whenever you check a SQLite return code. Often this will make it much easier to diagnose why a call failed.

How to store & retrieve NSArray object in sqlite database in objective c

The easiest way to achieve this is convert the array to JSON string and store the string in database and while fetching the data convert the JSON string to array again.

Array to JSON

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayObject options:NSJSONWritingPrettyPrinted error:nil]
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

JSON to Array

NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *arrayObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];


Related Topics



Leave a reply



Submit