计数 table 与关系 vb.net

count table with relationship vb.net

我有 2 个数据库 table,分别是办公室和状态。状态包括有缺陷、缺少零件和丢失。我想要发生的是,每当我选择一个办公室时,该办公室的缺陷、缺失部件和丢失的物品将被计算并显​​示在文本框或标签中。

截图:

sqlconnection.Open() 
Dim cmd As New MySqlCommand("Select Count(*) from cpfrtsdata where office = '" & ComboBox1.Text & "' ", sqlconnection) 
Dim i As Integer = cmd.ExecuteScalar() 
cmd = Nothing 
sqlconnection.Close() 
Label3.Text = i 

我要检查的第一件事是确认您正在从组合框中取回一个值。单步执行调试器并验证预期值。然后检查以确保您从查询中获取值。为您的控件起一个比 ComboBox1 和 Label3 更好的名称,使用默认名称很容易使用错误的控件。

而且我会从使用文本 属性 切换到 SelectedItem 以从控件取回值。

MS Docs 关于组合框的说法是:

You can use these properties to manage the currently selected item in the list, the Text property to specify the string displayed in the editing field, the SelectedIndex property to get or set the current item, and the SelectedItem property to get or set a reference to the object.

Dim officeString As String = ComboBox1.SelectedItem.ToString()

此外,您需要在查询中使用参数来防止 SQL 注入攻击

Select Count(*) from cpfrtsdata where office = 'Carpentry Shop' 将使 return 个办公室的记录数等于 Carpentry Shop。为了获得每个 status 的总数,您需要多次发出 SQL 事务,如下所示:

Select Count(*) from cpfrtsdata where office = 'Carpentry Shop' and status = 'Defective'
Select Count(*) from cpfrtsdata where office = 'Carpentry Shop' and status = 'Lost'

等等。或者您可以修改 SQL 以在一次交易中检索所有内容:

Select 
    sum(case status when 'Defective' then 1 else 0 end) as TotalDefective,
    sum(case status when 'Lost' then 1 else 0 end) as TotalLost,
    sum(case status when 'Missing Parts' then 1 else 0 end) as TotalMissingParts
from cpfrtsdata
where office = 'Carpentry Shop'
group by office

由于此查询 return 是 table,您需要使用 MySqlDataAdapter or cmd.ExecuteReader