嘿所有人我是asp.net的新手,我想从数据库中选择数据并将数据存储在VB中的DataTable而不是C#中,但我似乎无法理解如何连接。任何人都可以帮我尝试连接到访问数据库吗?我很迷茫,已经好几天了。如果不是它的确定。
感谢您的阅读。
布伦特
Public Function CheckUser(ByVal p_strUserNAME As String, ByVal p_Password As String) As Boolean
Dim blnAdminUser As Boolean = False
Dim SQLQuery As String = "SELECT Username, Password FROM HomelessUsers WHERE Username = " & p_strUserNAME & " AND Password = " & p_Password
Dim MDBConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\HomelessCapstone\HomelessCapstone\HomelessCapstone\APP_Data\Homeless.accdb;Persist Security Info=True"
Dim ds As New DataSet
Dim cnn As OleDbConnection = New OleDbConnection(MDBConnectionString)
cnn.Open()
Dim cmd As New OleDbCommand(SQLQuery, cnn)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, "HomelessUsers")
cnn.Close()
'Dim DatatableTest As DataTable = ds.Tables("HomelessUsers")
'Dim Row As DataRow = Nothing
'Dim Item(2) As String
'For Each Row In DatatableTest.Rows
'item()
' Next
Return blnAdminUser
End Function
答案 0 :(得分:0)
基本上,有两种方法可以解决它。 一种是使用ADO(访问数据库对象),它具有一个非常有用的向导,可以帮助您将访问数据库连接到程序并为控件设置数据源, 或者您可以使用System.Data.OLEDb(我更喜欢这个,因为它让我可以更好地控制我的系统)
Dim accessconn As New _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & pathofAccessFile)
Try
accessconn.Open()
MsgBox("Access succesfully connected")
accessconn.Close()
Return 0
Catch ex As Exception
accessconn.Close()
MsgBox("There is something wrong with the path provided.")
Return 1
End Try
你需要了解使用OLEDb类,所以这里有一些东西可以帮到你。 http://msdn.microsoft.com/en-us/library/System.Data.OleDb(v=vs.110).aspx
记下OLEDbCommand(执行SQL字符串),OLEDbDataAdapter(将数据从DB转换为Datagridview)和OLEDbDataReader(我用它来从数据库中选择数据)。
也许是为了帮助您更好地理解您的问题,以下是我如何使用DataReader类的示例:
Public Sub AccesstoGridd(ByVal utos As String, ByVal pathh As String, ByVal gridd As DataGridView, ByVal ngalan As String)
Dim accessconn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & pathh)
Try
Dim sqlutos As New System.Data.OleDb.OleDbCommand(utos, accessconn)
Dim idcounter As Integer = 0
accessconn.Open()
Dim reader As System.Data.OleDb.OleDbDataReader
reader = sqlutos.ExecuteReader
While reader.Read
idcounter = idcounter + 1
gridd.Rows.Add(idcounter, reader(0), reader(1), reader(2), reader(3), reader(4), reader(5), ngalan)
End While
reader.Close()
accessconn.Close()
Catch ex As Exception
accessconn.Close()
MsgBox("There is something wrong with the Access file selected." & vbNewLine & ex.ToString, MsgBoxStyle.Exclamation, "MDB file unrecognized.")
End Try
End Sub