How to import .sqlite3 / .sqlite file into ios app?

I had an excel file.

I converted this file to .csv format and imported this file to the database and converted it to a .sqlite file.

So the question is:

Is there any way to import it into ios app and manipulate data.

Is it possible to use it as kernel data or import this file into the main data.

Please direct any good textbook, preferably a video tutorial or some other good one.

+6
source share
3 answers

You can use it directly with the FMDB library: https://github.com/ccgus/fmdb Another option is to import this file into the main data, but it is a bit complicated. You can do this if you follow these steps:

  • Create an empty SQLite database in your application and run the application in the simulator.
  • Open the simulator directory on your computer and find the SQLite database file.
  • View it using the SQLite command line tool or something like the "GUI Data Browser" tool ( http://sqlitebrowser.sourceforge.net/ ).
  • Import data into this database file without changing the structure and data in the metadata of the master data.
  • Finally, you have an SQLite database file ready for use with master data. So you placed it in your application.
  • When you start the application for the first time, you must copy the SQLite database file to the appropriate directory (you know where you should place your file - you already found it in the application directory for the simulator) before setting up the base data stack.

It sounds a little complicated, but it works;)

Good article on delivering pre-populated data for master data: http://www.objc.io/issue-4/importing-large-data-sets-into-core-data.html

+4
source

Update

Check out the updated answer.

Is there a way to import it (SQLite) into an ios application and manage the data?

You can import the sqlite file into Xcode by simply adding it as a resource using "Add a new file" ... However, you would have limited ability to use it in conjunction with Core Data (unless it was created using Core Data). Consider the objc.io article mentioned earlier that describes how to work with pre-populated data in an Xcode project. Here is the relevant section of this article.

NSFileManager* fileManager = [NSFileManager defaultManager]; NSError *error; if([fileManager fileExistsAtPath:self.storeURL.path]) { NSURL *storeDirectory = [self.storeURL URLByDeletingLastPathComponent]; NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:storeDirectory includingPropertiesForKeys:nil options:0 errorHandler:NULL]; NSString *storeName = [self.storeURL.lastPathComponent stringByDeletingPathExtension]; for (NSURL *url in enumerator) { if (![url.lastPathComponent hasPrefix:storeName]) continue; [fileManager removeItemAtURL:url error:&error]; } // handle error } NSString* bundleDbPath = [[NSBundle mainBundle] pathForResource:@"seed" ofType:@"sqlite"]; [fileManager copyItemAtPath:bundleDbPath toPath:self.storeURL.path error:&error]; NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary; NSString* bundleVersion = [infoDictionary objectForKey:(NSString *)kCFBundleVersionKey]; NSString *seedVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"SeedVersion"]; if (![seedVersion isEqualToString:bundleVersion]) { // Copy the seed database } // ... after the import succeeded [[NSUserDefaults standardUserDefaults] setObject:bundleVersion forKey:@"SeedVersion"]; 

Assuming you need to import a CSV file, not Excel or SQLite ... Since this is a common question, here is a simple parser that you can use to include CSV data in your Xcode project.

 func parseCSV (contentsOfURL: NSURL, encoding: NSStringEncoding, error: NSErrorPointer) -> [(name:String, detail:String, price: String)]? { // Load the CSV file and parse it let delimiter = "," var items:[(name:String, detail:String, price: String)]? if let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) { items = [] let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] for line in lines { var values:[String] = [] if line != "" { // For a line with double quotes // we use NSScanner to perform the parsing if line.rangeOfString("\"") != nil { var textToScan:String = line var value:NSString? var textScanner:NSScanner = NSScanner(string: textToScan) while textScanner.string != "" { if (textScanner.string as NSString).substringToIndex(1) == "\"" { textScanner.scanLocation += 1 textScanner.scanUpToString("\"", intoString: &value) textScanner.scanLocation += 1 } else { textScanner.scanUpToString(delimiter, intoString: &value) } // Store the value into the values array values.append(value as! String) // Retrieve the unscanned remainder of the string if textScanner.scanLocation < count(textScanner.string) { textToScan = (textScanner.string as NSString).substringFromIndex(textScanner.scanLocation + 1) } else { textToScan = "" } textScanner = NSScanner(string: textToScan) } // For a line without double quotes, we can simply separate the string // by using the delimiter (eg comma) } else { values = line.componentsSeparatedByString(delimiter) } // Put the values into the tuple and add it to the items array let item = (name: values[0], detail: values[1], price: values[2]) items?.append(item) } } } return items } 

( Source of article )

Another option is to use the Core Data Editor tool, originally mentioned in the Ray W. tool list. This graphics editor attempts to facilitate the import of CSV data.

Is there a way to use it as kernel data or import this file into the main data?

Thus, the SQLite database does not match the underlying data (which is persistence on the graphical object ...). I was about to enter my distribution here, but Apple 's Basic Data says it's better than I could ...:

How to use an existing SQLite database with basic data?

You do not do. Although Core Data supports SQLite as one of its persistent storage types, the database format is confidential. You cannot create a SQLite Database using your own SQLite API and directly use it with Core Data (and you should not manipulate your existing SQLite Core Data Data Warehouse using your own SQLite API). If you have an existing SQLite database, you need to import it into the master data warehouse (see the "Effective Import" section). Data).

So the official answer. All that has been suggested is just a way around the fact that you should not do this.

However, given that you also have a CSV file, you have other options. I previously created a file reader to examine the contents of a CSV file using a stream reader. Here is the gist , however my file probably had a different formatting, so this probably needs to be configured. You can also use any object that reads the contents of a file. For instance; a much simpler technique comes to mind:

  • Use initWithContentsOfFile in an NSString class
  • Gives you a string with CSV in memory
  • Iterate a line for each line
  • Scroll through the line with commas and do something with each piece of data.

NSString * fileContents = [NSString stringWithContentsOfFile: @ "myfile.txt"]; NSArray * lines = [fileContents componentsSeparatedByString: @ "\ n"]; // loop and break each line in the string array into payloads

Nsstring

Let's say you really want to use SQLite in iOS, despite the warnings ... You can add the sqlite3 library to your project. Full details on how to use SQLite instead of Core Data. One of the many online guides on AppCoda

The basics are described ( example project ):

Preservation...

 - (IBAction)saveInfo:(id)sender { // Prepare the query string. NSString *query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', '%@', %d)", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]]; // Execute the query. [self.dbManager executeQuery:query]; // If the query was successfully executed then pop the view controller. if (self.dbManager.affectedRows != 0) { NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows); // Pop the view controller. [self.navigationController popViewControllerAnimated:YES]; } else{ NSLog(@"Could not execute the query."); } } 

Editing...

 -(void)loadInfoToEdit{ // Create the query. NSString *query = [NSString stringWithFormat:@"select * from peopleInfo where peopleInfoID=%d", self.recordIDToEdit]; // Load the relevant data. NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]]; // Set the loaded data to the textfields. self.txtFirstname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"firstname"]]; self.txtLastname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"lastname"]]; self.txtAge.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"age"]]; } 

Removing ...

 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the selected record. // Find the record ID. int recordIDToDelete = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue]; // Prepare the query. NSString *query = [NSString stringWithFormat:@"delete from peopleInfo where peopleInfoID=%d", recordIDToDelete]; // Execute the query. [self.dbManager executeQuery:query]; // Reload the table view. [self loadData]; } } 

Re: I apologize for any good tutorial, preferably video tutorials or some other good one .

The following guide should fill your needs. There are several tutorials on this subject, on which you can read on the website www.lynda.com for a detailed introduction to creating an iOS application using SQLite (some of them are related to full access, however, search Youtube as they publish movie samples covering these topics all the time).

http://www.youtube.com/watch?v=bC3F8a4F_KE (see 1:17 on video)

+3
source

If you have a .sql file, you simply import it into your project by going to File - Add Files. Also, keep in mind that if you leave your .sql file in your package, it will be read-only. So, if you do not want this to be read-only, you must create a new group and place your .sql there.

0
source

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


All Articles