【问题标题】:How to import an .sqlite3/.sqlite file to ios application?如何将 .sqlite3/.sqlite 文件导入 ios 应用程序?
【发布时间】:2013-10-31 20:10:57
【问题描述】:

我有一个 excel 文件。

我已将该文件转换为 .csv 格式,并将该文件导入 base 并将其转换为 .sqlite 文件。

所以问题是:

有什么方法可以将其导入 ios 应用程序并操作数据。

有没有办法像核心数据一样使用它或将该文件导入核心数据。

请参考任何好的教程,最好是视频教程或其他一些好的教程。

【问题讨论】:

  • 如果有人需要知道如何添加这个文件并且通过给定的ans不明白可以在下面评论

标签: iphone ios objective-c sqlite


【解决方案1】:

您可以直接使用 FMDB 库:https://github.com/ccgus/fmdb 另一种选择是将该文件导入核心数据,但这有点棘手。如果您按照以下步骤操作,您就可以做到:

  1. 在您的应用程序中创建空的 SQLite 数据库并在模拟器中运行您的应用程序。
  2. 在您的计算机上打开模拟器目录并找到 SQLite 数据库文件。
  3. 使用 SQLite 命令行工具或类似“SQLite 数据浏览器”GUI 工具 (http://sqlitebrowser.sourceforge.net/) 来查看它。
  4. 将您的数据导入此数据库文件,而无需更改核心数据元表中的结构和数据。
  5. 最后,您已经准备好用于核心数据的 SQLite 数据库文件。因此,您将其放入您的应用程序包中。
  6. 在第一次启动应用程序时,您应该在配置核心数据堆栈之前将您的 SQLite 数据库文件复制到适当的目录(您知道应该将文件放在哪里 - 您已经在模拟器应用程序目录中找到了它)。

这听起来有点复杂,但它确实有效;)

关于运送核心数据的预填充数据的好文章:http://www.objc.io/issue-4/importing-large-data-sets-into-core-data.html

【讨论】:

    【解决方案2】:

    更新

    请注意更新后的回复。

    有什么方法可以将它 (SQLite) 导入 ios 应用程序并操作数据?

    您可以将 sqlite 文件导入 Xcode,只需使用 Add New File 将其添加为资源...但是您将无法与 Core Data 一起使用它(除非它是使用 Core Data 创建的)。可以查看前面引用的objc.io article,其中介绍了如何处理 Xcode 项目中的预填充数据。这是那篇文章的相关部分。

    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"];
    

    假设想要导入 CSV 文件而不是 Excel 或 SQLite... 由于这是一个常见问题,这里有一个简单的解析器,可以用来将 CSV 数据合并到 Xcode 中项目。

    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 (e.g. 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 article)

    另一种选择是使用最初在 Ray W.list of tools 中提到的核心数据编辑器工具。这个GUI editor 试图使处理 CSV 数据导入更容易。

    有没有办法像核心数据一样使用它或将该文件导入核心数据?

    所以 SQLite 数据库与 Core Data 不同(它是一个对象图持久性......)。我正要在这里大肆抨击,但 Apple 的 Core Data FAQ 说得比我好......:

    如何将现有的 SQLite 数据库与 Core Data 结合使用?

    你没有。尽管 Core Data 支持 SQLite 作为其持久性之一 存储类型,数据库格式是私有的。你不能创建一个 SQLite 数据库使用原生 SQLite API 并直接与 Core 一起使用 数据(也不应该操作现有的 Core Data SQLite 存储 使用本机 SQLite API)。如果你有一个现有的 SQLite 数据库,你 需要将其导入核心数据存储(请参阅有效导入 数据)。

    所以这是官方的答案。提供的其他任何东西都只是一种解决人们不应该这样做的事实的方法。

    但是,鉴于您还有一个 CSV 文件,您还有其他一些选择。过去,我构建了一个文件阅读器来使用流阅读器检查 CSV 文件的内容。这是其中的gist,但是我的文件可能有一些其他格式,所以这可能需要调整。您还可以查看使用任何读取文件内容的对象。例如;想到一个更简单的技术:

    1. NSString 类上使用 initWithContentsOfFile
    2. 为您提供内存中包含 CSV 的字符串
    3. 为每一行迭代字符串
    4. 使用逗号遍历该行并对每条数据执行一些操作

    NSString *fileContents = [NSString stringWithContentsOfFile:@"myfile.txt"]; NSArray *lines = [fileContents componentsSeparatedByString:@"\n"]; //循环并将lines数组中的每一行拆分为有用的数据

    假设您真的想在 iOS 中使用 SQLite,尽管有警告...您可以将 sqlite3 库添加到您的项目中。有关如何使用 SQLite 而不是 Core Data 的完整详细信息。众多在线教程之一是AppCoda

    涵盖了基础知识 (sample project):

    正在保存...

    - (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.");
        }
    }
    

    正在编辑...

    -(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"]];
    }
    

    正在删除...

    -(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: 请参考任何好的教程,最好是视频教程或一些 其他不错的

    以下教程应该可以满足您的需求。有很多关于这个主题的教程,你可以查看 www.lynda.com,详细了解如何使用 SQLite 构建 iOS 应用程序(完全访问需要一些费用,但是搜索 Youtube,因为他们发布了涵盖这些主题的示例电影时间)。

    http://www.youtube.com/watch?v=bC3F8a4F_KE(见视频中的 1:17)

    【讨论】:

      【解决方案3】:

      如果您有一个 .sql 文件,您只需转到文件 - 添加文件将其导入您的项目。 另外,请记住,如果您将 .sql 文件留在包中,它将是只读的。 因此,除非您希望它是只读的,否则您应该创建一个新组并将您的 .sql 放在那里。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 2012-11-17
        • 2012-08-05
        • 2012-02-10
        相关资源
        最近更新 更多