Import and query through SQLite database in Swift - iOS

I am creating an application that uses a large database with 5 different tables. I want to import this database into the application package and be able to query tables. The user will not edit the database, so adding or removing entries is not required.

What would be the best way to add a database to an application?

+8
source share
2 answers

The process is as follows:

  • Add the database to your package. When you drag it into your project, you can add it to the target that represents your main application. In addition, review the target settings, click "Phase Build" and confirm that the database appears in the "Copy Copy Resources" list.

  • Use a framework like FMDB to make your life easier. This is written in Objective-C, but works fine in Swift too. What you need to do:

    • Copy the .h and .m files for FMDB into your project;

    • When prompted to create a "bridge header", do this:

    • Add the following line to the bridge header:

      #import "FMDB.h" 

    By following these steps, you can use this infrastructure developed in Objective-C in your Swift projects.

  • Now you can write your Swift code using the FMDB framework. For example, the Swift code to open a database, select the columns x , y and z from a table called test , will look like this:

     let path = NSBundle.mainBundle().pathForResource("test", ofType:"sqlite") let database = FMDatabase(path: path) if !database.open() { print("Unable to open database") return } if let rs = database.executeQuery("select * from test", withArgumentsInArray: nil) { while rs.next() { let x = rs.stringForColumn("x") let y = rs.stringForColumn("y") let z = rs.stringForColumn("z") print("x = \(x); y = \(y); z = \(z)") } } else { print("executeQuery failed: \(database.lastErrorMessage())") } database.close() 
+9
source

Swift only. Objective-C files are not required.

Here is another solution that uses SQLite.swift instead of FMDB .

1 .: Get the correct path to your database file

Do not save the database file in the Resources folder, but add it to the Copy Set Resources list in the Build Phases setting of the current target. If your file is called myDb.db you can get the correct path, for example:

 let dbUrl = Bundle.main.url(forResource: "myDb", withExtension: "db")! let dbPath = dbUrl.path 

2 .: Access to your database (without copying)

Now you can access your database without having to (manually?) Copy it. Just use the SQLite.swift library:

 db = try! Connection(dbPath) 

Notes: The only thing I have not verified yet is writing to the database. At least read-only access works like a charm, though.

0
source

Source: https://habr.com/ru/post/976681/


All Articles