VB.Net问题
我正在做一个VB.Net项目,试图让它从数据库中提取数据。我的数据库位于我的bin文件夹中,但我不知道具体的路径。我正在使用的代码如下所示VB.Net问题,vb.net,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
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文件中提取数据。我知道显示的当前位置不正确。如果数据库与可执行文件一起位于bin文件夹中,则可以执行以下操作:
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
' 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
那么,这是一个MS Access数据库?这并不能解决他的问题-他需要正确构造strPath变量。Dim strPath As String=Provider=Microsoft.ACE.OLEDB.12.0;&数据源=C:\Documents and Settings\user\Desktop\programs6\ApprovedTravelRequests\Travel.accdb完整路径您是正确的。。谢谢