首页 > 解决方案 > 将msql中的数据拉到tableview

问题描述

我想将我从 Mssql 获取的数据打印到 tableview。但我无法将这些数据打印到 tableview。我要打印的数据是一个邮件地址,一个字符串值。我正在使用 mssql 数据库。如何打印从 msql 获取的数据到 tableview?

class MakaleController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var makaleTable: UITableView!
    var stringvalue: [String] = []
    override func viewDidLoad() {
           super.viewDidLoad()
        let client = SQLClient.sharedInstance()!
                         client.connect("asd", username: "asd", password: "asd", database: "asd") { success in
                         client.execute("SELECT Email FROM and", completion: { (_ results: ([Any]?)) in
                          for table in results as! [[[String:AnyObject]]] {
                              for row in table {
                                  for (columnName, value) in row {
                                           print(value)
                                          if let intVal = value as? Int {
                                               self.stringvalue.append(String(intVal))
                                            DispatchQueue.main.async { self.makaleTable.reloadData() }}} }}
                          client.disconnect()
                      })
                  }
    }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return stringvalue.count
        }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         
       let cell:UITableViewCell = self.makaleTable.dequeueReusableCell(withIdentifier: "makalecell") as! UITableViewCell
            cell.textLabel?.text = self.stringvalue[indexPath.row]
                    return cell
        }
}

标签: swift

解决方案


首先,检查您是否成功地将原始值转换为Int(这就是我添加第二个 print 语句的原因),然后在所有循环之后重新加载表(而不是像您所做的那样从它们内部):

override func viewDidLoad() {
    super.viewDidLoad()

    let client = SQLClient.sharedInstance()!

    client.connect("asd", username: "asd", password: "asd", database: "asd") { success in

        client.execute("SELECT Email FROM and", completion: { (_ results: ([Any]?)) in

            for table in results as! [[[String:AnyObject]]] {

                for row in table {

                    for (columnName, value) in row {

                        print(value) // prints correctly as NVARCHAR

                        if let val = value as? String { // edit: skip casting as Int, go straight to String
                            stringvalue.append(val)
                        }

                    }

                }

            }

            // reload table once after all loops are complete
            DispatchQueue.main.async {
                self.makaleTable.reloadData()
            }

            client.disconnect()

        })

    }

}

推荐阅读