2010-04-08 77 views
0

我正在研究一個VB.Net項目並試圖從數據庫中獲取數據。我的數據庫位於我的bin文件夾中,但我不知道如何執行此操作的確切路徑。我使用的代碼如下所示VB.Net問題

 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文件中提取數據。我知道顯示的當前位置不正確。

+0

所以,這是一個MS Access數據庫? – 2010-04-08 16:06:58

+0

是的,它是MS Access – Michael 2010-04-08 16:36:48

回答

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 
+0

Dim strPath As String =「Provider = Microsoft.ACE.OLEDB.12.0;」 &「Data Source = C:\ Documents and Settings \ user \ Desktop \ programs6 \ ApprovedTravelRequests \ Travel.accdb」 您正確的完整路徑。 – Michael 2010-04-08 17:16:47

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 
+0

這不能解決他的問題 - 他需要正確構建「strPath」變量。 – 2010-04-08 16:19:45