如何在Swift中用MS SQL查询结果填充数组并在TableView展示
解决SQL查询结果填充数组并在TableView展示的问题
Hey there! Great job getting your MS SQL connection up and running—seeing those UserId values print in the debugger means you're already halfway there 😊 Let's fix how you populate the uNames array and get those values showing up in your TableView.
核心问题与解决方案
Right now, you're printing the value but not adding it to your uNames array. Plus, since SQL operations run on a background thread, you need to make sure you update your UI (reload the TableView) on the main thread. Here's how to adjust your code:
修改后的代码片段
Focus on updating the execute closure inside your btnUserAct method:
@IBAction func btnUserAct(_ sender: Any) { client = SQLClient.sharedInstance()! client.delegate = self client.connect(strIP,username: strUName,password: strPass,database: strDBName){ success in if success { self.client.execute("Select UserId from Usertbl order by Id") { results in // 1. 先清空数组,避免重复点击按钮时数据累加 self.uNames.removeAll() for table in results as! [[[String:AnyObject]]] { for row in table { // 2. 直接提取UserId列的值,不需要遍历所有键值对 if let userId = row["UserId"] as? String { self.uNames.append(userId) } else if let userIdNumber = row["UserId"] as? Int { // 如果UserId是数字类型,转换为String后添加 self.uNames.append(String(userIdNumber)) } } } // 3. 必须在主线程更新UI(TableView刷新) DispatchQueue.main.async { self.userListTableView.reloadData() } self.client.disconnect() } } } }
关键细节解释
- 清空数组:每次点击按钮查询时,先调用
removeAll(),防止旧数据和新数据混在一起。 - 精准提取列值:你明确查询的是
UserId列,所以直接通过row["UserId"]取值比遍历所有键值对更高效,也避免了无关数据。 - 类型转换处理:数据库里的
UserId可能是字符串或数字类型,所以我们做了两种情况的判断,确保能正确转成String添加到数组。 - 主线程更新UI:SQLClient的回调是在后台线程执行的,iOS要求所有UI操作必须在主线程,所以用
DispatchQueue.main.async包裹reloadData(),保证TableView能正确刷新。
额外检查项
如果你的TableView还是没显示数据,确认这几点:
- 在
viewDidLoad()里设置TableView的代理和数据源:override func viewDidLoad() { super.viewDidLoad() // ... 其他代码 ... userListTableView.delegate = self userListTableView.dataSource = self // 如果你的cell是纯代码创建而不是Storyboard注册的,加上这句: // userListTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } - 确认Storyboard里的TableView cell的
Identifier确实是cell,和你在cellForRowAt里用的一致。
这样修改后,你的uNames数组会被正确填充,TableView也会显示所有UserId值啦!
内容的提问来源于stack exchange,提问作者halil balcıoğlu
相关产品推荐
相关产品推荐

