数据库查询速度慢:使用VB.net连接到Access

时间:2016-02-16 09:44:25

标签: vb.net

我有一个程序,它只允许一定数量的并发用户同时使用该程序。为此,我在访问数据库中有一个表,用于保存正在使用该程序的每个用户。现在虽然这确实有效,但查询似乎运行得非常慢,我确信它与数据库函数有关,因为它在我实现之前运行正常。

以下是我的功能:

Public Function openDB() As Boolean
    cnn.Open()
    Return True
End Function

Public Function closeDB() As Boolean
    cnn.Close()
    Return True
End Function

然后有检查数据库的功能。这是我认为可能会绊倒的地方,因为我在这里运行了2个查询:

Public Function CheckLicence() As Boolean
    Dim result As Boolean = HandleRegistry()
    If result = True Then
        Dim _table As String = "Users"
        Dim query As String = "SELECT * FROM " & _table & " WHERE Machine_ID='" & CpuId() & "'"
        Dim sizeQuery As String = "SELECT COUNT(*) FROM " & _table
        Dim NoUsers As Integer = 0
        Dim ds As New DataSet

        Dim dr As OleDbDataReader
        Dim cmd As New OleDbCommand(query, cnn)
        dr = cmd.ExecuteReader


        Dim sizeCdm As New OleDbCommand(sizeQuery, cnn)
        NoUsers = sizeCdm.ExecuteScalar()

        If dr.Read() Then
            Return True
        Else
            If NoUsers < My.Settings.NoUsers Then

                addToDB()
            Else
                MsgBox("Too many users are currently using this program. Clear a user and try again.")

                Return False
            End If
        End If

    Else
        MsgBox("Your licence has expired, contact support to purchase a new licence.")
        Return False
    End If
    Return True
End Function

要添加和删除我必须得到cpu id,我发现它的代码在这里它确实有效,但也许这可能是缓慢的部分,我实际上不知道这是否是正确的获取方式

 Public Sub addToDB()
    Dim _table As String = "Users"
    Dim query As String = "INSERT INTO " & _table & " ([User], [Machine_ID]) VALUES (?,?)"
    Dim ds As New DataSet

    Dim cmd As New OleDbCommand(query, cnn)
    cmd.Parameters.AddWithValue("?", Environment.UserName)
    cmd.Parameters.AddWithValue("?", CpuId())
    cmd.ExecuteNonQuery()


End Sub
Public Sub RemoveFromDB()
    Dim _table As String = "Users"

    Dim query As String = "DELETE * FROM " & _table & " WHERE Machine_ID='" & CpuId() & "'"
    Dim ds As New DataSet

    Dim cmd As New OleDbCommand(query, cnn)
    cmd.ExecuteNonQuery()

End Sub
Private Function CpuId() As String
    Dim computer As String = "."
    Dim wmi As Object = GetObject("winmgmts:" &
        "{impersonationLevel=impersonate}!\\" &
        computer & "\root\cimv2")
    Dim processors As Object = wmi.ExecQuery("Select * from " &
        "Win32_Processor")

    Dim cpu_ids As String = ""
    For Each cpu As Object In processors
        cpu_ids = cpu_ids & ", " & cpu.ProcessorId
    Next cpu
    If cpu_ids.Length > 0 Then cpu_ids =
        cpu_ids.Substring(2)

    Return cpu_ids
End Function

2 个答案:

答案 0 :(得分:1)

答案:

  

如何全局存储cpuID并仅获取一次。此外,对需要处理的任何内容使用Using&gt;构造。最后,在您的方法周围运行一些StopWatches&gt;以查看哪一个很慢或只是通过每个调试到>找到慢速方法。 - Andrew Mortimer

将获取cpuID的调用移至程序初始化,以便在启动时运行。这使它比以前运行得快得多。

答案 1 :(得分:1)

如何全局存储cpuID并仅获取一次。此外,对需要处理的任何内容使用Using构造。最后,在你的方法周围运行几个StopWatches,看看哪一个很慢,或者只是通过每一个调试来找到慢速方法。