来自Access DB的高效统计信息

时间:2019-11-25 12:37:48

标签: vb.net

我正在从Access DB中提取统计信息并使用以下内容:

'''
    countBP = Convert.ToInt32(New OleDbCommand(commandBP.ToString, con).ExecuteScalar)
    countWP = Convert.ToInt32(New OleDbCommand(commandWP.ToString, con).ExecuteScalar)
    countHP = Convert.ToInt32(New OleDbCommand(commandHP.ToString, con).ExecuteScalar)
'''

其中:

'''
    command = ""SELECT COUNT(*) FROM Employees WHERE Archived = 'N' AND ID > 2"
    commandBP = command.ToString + " AND Ethnic = 'B' AND EmployeeType = 1"
    commandWP = command.ToString + " AND Ethnic = 'W' AND EmployeeType = 1"
    commandHP = command.ToString + " AND Ethnic = 'H' AND EmployeeType = 1"
'''

我的问题是;这样有效吗?我将分别获取20多个统计信息,随着数据库的增长,加载它似乎花费了越来越多的时间。我想知道将“ SELECT * FROM Employees”添加到数据集中然后进行过滤是否会是更好的方法?

1 个答案:

答案 0 :(得分:3)

查询中唯一可变的部分是“种族”字段。建议在该字段上使用Group By子句

command = "SELECT Ethnic, COUNT(*) FROM Employees 
           WHERE Archived = 'N' AND ID > 2 AND EmployeeType = 1
           GROUP BY Ethnic" 

现在,这将数据库调用减少到一个调用,您可以使用来检索数据

Dim data as Dictionary(Of String, Int32) = new Dictionary(Of String, Int32)()
OleDbCommand cmd = New OleDbCommand(command, con)
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
    data(reader.GetString(0)) = reader.GetInt32(1)
End While

此时,您可以从字典中获取计数值

Dim countBP as Integer
data.TryGetValue("B", countBP) 
....

请注意,您应该使用TryGetValue方法从数据库中提取值,因为如果没有针对民族=“ B”的记录,则字典中将不会存在键“ B”的条目,但是TryGetValue将使CountBP保持初始化状态其默认值为零。