VB.Net问题

时间:2010-04-08 16:03:20

标签: vb.net

我正在开发一个VB.Net项目并试图让它从数据库中提取数据。我的数据库位于项目中的bin文件夹中,但我不知道如何操作的确切路径。我正在使用的代码如下所示

       Private Sub btnTotalTravelCost_Click(ByVal sender As System.Object, ByVal e As     System.EventArgs) Handles btnTotalTravelCost.Click
        'strsql is a sql statement that selects all the fields from the 
       'ApprovedTravelRequest table

        Dim strSql As String = "SELECT * FROM ApprovedTravelRequests "

        'strPath provides the database type and path of the Travel database.
        Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data     Source=c:\Travel.accdb"
        Dim odaTravel As New OleDb.OleDbDataAdapter(strSql, strPath)
        Dim DatCost As New DataTable
        Dim intCount As Integer
        Dim decTotalCost As Decimal = 0D

        'The DataTable name datCost is filled with the data
        odaTravel.Fill(DatCost)

        'The connection to the databsise is disconnected
        odaTravel.Dispose()

        For intCount = 0 To DatCost.Rows.Count - 1
            decTotalCost += Convert.ToDecimal(DatCost.Rows(intCount)("Travel Cost"))
        Next

        Me.lblTotalTravelCost.Visible = True
        Me.lblTotalTravelCost.Text = "The Total Approved Travel Cost is " & decTotalCost.ToString("C")




    End Sub
End Class

有人能够解释如何做到这一点吗?我想从Bin文件中提取数据。我知道显示的当前位置不正确。

2 个答案:

答案 0 :(得分:0)

Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=c:\Travel.accdb"
Dim strSql As String = "SELECT * FROM ApprovedTravelRequests"
Dim decTotalCost As Decimal = 0.0
Using connect As New OleDb.OleDbConnection(strPath)
    Using command As New OleDb.OleDbCommand(strSql, connect)
        connect.Open()
        Using reader As OleDb.OleDbDataReader = command.ExecuteReader()
            If reader.HasRows Then
                While reader.Read()
                    decTotalCost += Convert.ToDecimal(reader(0))
                End While
            End If
            Me.lblTotalTravelCost.Visible = True
            Me.lblTotalTravelCost.Text = "The Total Approved Travel Cost is " & decTotalCost.ToString("C")
        End Using
    End Using
End Using

答案 1 :(得分:0)

如果数据库位于bin文件夹中(包含可执行文件),则可以执行以下操作:

' Get the current directory (where the exe resides)
Dim folder As String = System.AppDomain.CurrentDomain.BaseDirectory
' Construct the full path to the DB (assuming it's with the exe)
folder = System.IO.Path.Combine(folder, "Travel.accdb")
' Build your connection string
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source=" & folder