我在将访问数据库中的值读入visual basic时遇到了一些困难。我正在使用Access和MS Visual Studio的最新版本。我总是遇到错误'NullReferenceException'并且无法加载记录:( plz help!
这是我的代码
Option Explicit On
Option Strict On
Imports System.Data.OleDb
Public Class frmMain
Private Sub btnDisplayAll_Click(sender As Object, e As EventArgs) Handles btnDisplayAll.Click
Dim oController As Controller = New Controller
Dim lsData = oController.displayAll()
Dim sCustomerDetails As String
For Each product In lsData
sCustomerDetails = CStr(product("customer_id"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("FirstName"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("LirstName"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("Address"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("PhoneNumber"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("eMail"))
sCustomerDetails = sCustomerDetails & " | " & CStr(product("DateOfBirth"))
Debug.Print(sCustomerDetails)
Next
End Sub
Private Sub sProductDetails(p1 As Object)
Throw New NotImplementedException
End Sub
End Class
Public Class Controller
Public Const CONNECTION_STRING As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Assignment1DB.accdb"
Public Function displayAll() As List(Of Hashtable)
Dim lsData As New List(Of Hashtable)
Dim oConnection As OleDbConnection = New OleDbConnection(CONNECTION_STRING)
Try
Debug.Print("Connection string: " & oConnection.ConnectionString)
oConnection.Open()
Dim oCommand As OleDbCommand = New OleDbCommand
oCommand.Connection = oConnection
'TODO
oCommand.CommandText = "SELECT * FROM customer ORDER BY customer_id;"
oCommand.Prepare()
Dim oDataReader = oCommand.ExecuteReader()
Dim htCustomerData As Hashtable
Do While oDataReader.Read() = True
htCustomerData("CustomerID") = CStr(oDataReader("customer_id"))
htCustomerData("FirstName") = CStr(oDataReader("firstname"))
htCustomerData("LastName") = CStr(oDataReader("lastname"))
htCustomerData("Address") = CStr(oDataReader("address"))
htCustomerData("PhoneNumber") = CStr(oDataReader("phone_number"))
htCustomerData("eMail") = CStr(oDataReader("email"))
htCustomerData("DateOfBirth") = CStr(oDataReader("dob"))
lsData.Add(htCustomerData)
Loop
Debug.Print("The Records were found.")
Catch ex As Exception
Debug.Print("Error: " & ex.Message)
MsgBox("The records couldn't be found.")
Finally
oConnection.Close()
End Try
Return lsData
End Function
结束班