Swift 5 SQLite到TableView

问题描述

我只想从sqlite数据库填充Tableview。非常感谢您的帮助。 我相信这个问题很容易解决,但由于缺乏Swift开发经验,所以我不能这样做。这是我一直在使用的代码

我认为缺少的部分是:

  • 创建新数组
  • sqlite数据追加到数组

因此,问题是:如何将数据库中的许多列附加到数组并在Table-view中显示它们。谢谢:)

快捷键5


import UIKit
import sqlite

class MyClass1: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {

    @IBOutlet var tableview: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    
    var db: OpaquePointer?
    
    var names = [
        "Sam","Mark","Kia","John"
    ]
    var filteredData : [String]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        filteredData = names
        
        // connect to database
        let fileURL = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!.appendingPathComponent("myDB.db",isDirectory: false)

        //opening the database
        if sqlite3_open(fileURL.path,&db) != sqlITE_OK {
            print("error opening database")
        }

        
        let queryString = "SELECT * FROM people"
        
        var stmt:OpaquePointer?
        
        if sqlite3_prepare(db,queryString,-1,&stmt,nil) != sqlITE_OK{
            let errmsg = String(cString: sqlite3_errmsg(db)!)
            print("error preparing insert: \(errmsg)")
            return
        }
        
        while(sqlite3_step(stmt) == sqlITE_ROW){
            let id = sqlite3_column_int(stmt,0)
            let name = String(cString: sqlite3_column_text(stmt,1))
            print("id:\(id) name:\(name)")
        }
        
        self.tableview.reloadData()
        
        
    }
    
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return filteredData.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
        
        cell.textLabel?.text = filteredData[indexPath.row]
        
        return cell
    }

    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        print("You clicked me! at \(indexPath.row)")
    }

    // MARK: search bar config
    
    func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
        print("search word entered!")
        
        filteredData = []
        
        if searchText == "" {
            filteredData = names
        } else {
        
            for name in names {
                if name.lowercased().contains(searchText.lowercased()) {
                    filteredData.append(name)
                }
            }
        }
        
        self.tableview.reloadData()
    }
    
    // called when keyboard search button pressed
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }

}

解决方法

创建一个新的自定义类型以保存sql表中的数据

struct People {
    let id: Int
    let name: String
}

在视图控制器中添加一个数组作为类属性

var people: [People] = []

,然后使用sql查询的结果填充该数组

while(sqlite3_step(stmt) == SQLITE_ROW){
    let id = sqlite3_column_int(stmt,0)
    let name = String(cString: sqlite3_column_text(stmt,1))
    people.append(People(id: id,name: name))
}

您将需要让您的filteredData数组也容纳People对象,并且需要更改过滤条件。

for person in people {
    if person.name.lowercased().contains(searchText.lowercased()) {
        filteredData.append(person)
    }
}