How to link a pre-populated database in quick

I know that there are many related posts, but I could notice that none of them explains how to do this, most of them say that I look at the documentation, I already looked, but it seems that there is not enough information about Swift

I have an old .db database with more than 60 thousand rows, three columns that I want to bring to my quick SQLite application using the FMDB wrapper, the application works on the iPhone, I tried to just drag and drop contacts.db onto, but I can’t get access to it. The application, when launched on the device, always launches a new database.

I copied the database to the support files folder and tried in the application folder, could not access from either

Is there anyone who did this and wanted to show me how to do this?

In general, I am looking to insert my contacts.db into the application (bundle) so that I can access the device, not the simulator. I do not need to add the removal or edit contact.db in the device, the database is loaded with all the necessary information, the user will only be able to search and be able to display the results.

class ViewController: UIViewController { @IBOutlet weak var name: UITextField! @IBOutlet weak var address: UITextField! var databasePath = NSString() override func viewDidLoad() { super.viewDidLoad() if let resourceUrl = NSBundle.mainBundle().URLForResource("contacts", withExtension: "db") { if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) } let filemgr = NSFileManager.defaultManager() let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docsDir = dirPaths[0] as! String databasePath = docsDir.stringByAppendingPathComponent( "contacts.db") if !filemgr.fileExistsAtPath(databasePath as String) { let contactDB = FMDatabase(path: databasePath as String) if contactDB == nil { println("Error: \(contactDB.lastErrorMessage())") } if contactDB.open() { let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)" if !contactDB.executeStatements(sql_stmt) { println("Error: \(contactDB.lastErrorMessage())") } contactDB.close() } else { println("Error: \(contactDB.lastErrorMessage())") } } } 
+6
source share
3 answers

Swift 2 example

A few assumptions:

  • You added libsqlite3.tbd to your project correctly.
  • You have correctly added the sqlite database to your project.
  • You copied the required FMDB files to your project correctly.
  • You have a ViewController named ViewController.swift

In Xcode, open the ViewController.swift file and find the following code:

  override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. 

Add the following code below the comment and remember to change the database name on lines 4 and 5.

  // Start of Database copy from Bundle to App Document Directory let fileManager = NSFileManager.defaultManager() let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) let destinationSqliteURL = documentsPath.URLByAppendingPathComponent("sqlite.db") let sourceSqliteURL = NSBundle.mainBundle().URLForResource("sqlite", withExtension: "db") if !fileManager.fileExistsAtPath(destinationSqliteURL.path!) { // var error:NSError? = nil do { try fileManager.copyItemAtURL(sourceSqliteURL!, toURL: destinationSqliteURL) print("Copied") print(destinationSqliteURL.path) } catch let error as NSError { print("Unable to create database \(error.debugDescription)") } } // Let print the path to the database on your Mac // so you can go look for the database in the Finder. print(documentsPath) let db = FMDatabase(path: destinationSqliteURL.path) // Let open the database if !db.open() { print("Unable to open database") return } // Let run some SQL from the FMDB documents to make sure // everything is working as expected. if !db.executeUpdate("create table test(x text, y text, z text)", withArgumentsInArray: nil) { print("create table failed: \(db.lastErrorMessage())") } if !db.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["a", "b", "c"]) { print("insert 1 table failed: \(db.lastErrorMessage())") } if !db.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["e", "f", "g"]) { print("insert 2 table failed: \(db.lastErrorMessage())") } if let rs = db.executeQuery("select x, y, z 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("select failed: \(db.lastErrorMessage())") } db.close() 

Now you can run the project and copy your database.

Previous answer if it helps someone

The documentation for FMDB is pretty useful on this topic. Using the example here, the code below should work, assuming the following:

  • You are using Swift 1.2 or later.
  • You have correctly added FMDB to your project.
  • An SQLite database called contacts.db been added to the project.
  • In Build Phases , then Link Binary With Libraries , which you added libsqlite3.dylib .

     // // ViewController.swift // import UIKit class ViewController: UIViewController { @IBOutlet weak var name: UITextField! @IBOutlet weak var address: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let filemgr = NSFileManager.defaultManager() let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String let path = documentsFolder.stringByAppendingPathComponent("contacts.db") let database = FMDatabase(path: path) if !database.open() { println("Unable to open database") return } if !database.executeUpdate("create table test(x text, y text, z text)", withArgumentsInArray: nil) { println("create table failed: \(database.lastErrorMessage())") } if !database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["a", "b", "c"]) { println("insert 1 table failed: \(database.lastErrorMessage())") } if !database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", withArgumentsInArray: ["e", "f", "g"]) { println("insert 2 table failed: \(database.lastErrorMessage())") } if let rs = database.executeQuery("select x, y, z from test", withArgumentsInArray: nil) { while rs.next() { let x = rs.stringForColumn("x") let y = rs.stringForColumn("y") let z = rs.stringForColumn("z") println("x = \(x); y = \(y); z = \(z)") } } else { println("select failed: \(database.lastErrorMessage())") } database.close() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

To check, just use the Build and Run button, and you should see the simulator launch and the following results in the Xcode console:

 x = a; y = b; z = c x = e; y = f; z = g 

To display the console, enter Shift + CMD + R or go to the View menu β†’ Debug Area β†’ Activate Console

+6
source

Firstly, this does not apply to master data if you use FMDB.

Secondly, in fact it is quite simple.

In Xcode, you include the SQL file as a resource that is loaded into your application when it is created.

Then find the file using the [[NSBundle mainBundle] URLForResource:@"file" withExtension:@"sqlite"] . From there, you start with FMDB as usual.

If you want to write to this file, you will need to copy it to the recording location in the application sandbox.

Update 1

You place the file in the kit, but you do not copy it from the package and into the document directory before you try to open it. You need to copy it from the package if it does not exist in the document directory.

+2
source

If you use Core data, you should not use FMDB, use the shell only for applications using SQLite / database. If you use Swift, it is recommended to use a shell if you are not familiar with C ++ and databases.

+1
source

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


All Articles