swift - 将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
}
}
解决方案
首先,检查您是否成功地将原始值转换为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()
})
}
}
推荐阅读
- json - JSON 中的 Fluentd,多级嵌套转义 JSON 字符串
- css - 左侧全宽 col
- svn - SVN 结帐后和更新后消息
- sql - Python多行SQL语句,用单引号插入变量
- angular - Angular 7:遍历复杂对象并填充表格
- dc.js - 需要在单独的行中显示交叉过滤器数据数组值,而不是在一行中显示逗号分隔值
- r - 您能否在另一个参数化 rmd 报告中调用/呈现参数化 rmd 报告 - rmarkdown
- python-3.x - NppExec 命令和输出历史
- firebase - Firebase Cloud Firestore 生成编译错误
- asp.net-mvc - 当存在多个复选框时,Kendo 验证器总是返回 false