从Dataset Vb.Net中选择数据

时间:2013-01-13 04:47:22

标签: vb.net dataset

好的,先解释一下我做了什么。

首先,我将访问数据库导入到我的vb应用程序中,然后命名数据集等。

这就是我的dataSet的外观: 1张桌子    4列

到目前为止我有这个:

Dim ds As ElementsDataSet
    Dim dt As ElementsDataSet.ElementsDataTable
    Dim conn As SqlConnection = New SqlConnection("Data Source=|DataDirectory|\Elements.accdb")
    Dim selectString As String = "Select Atomic Mass FROM Elements WHERE No =" & mol
    Dim cmd As New SqlCommand(selectString, conn)
If conn.State = ConnectionState.Closed Then conn.Open()

Dim datareader As SqlDataReader = cmd.ExecuteReader()

While datareader.Read = True

    MessageBox.Show(datareader.Item("Atomic Mass"))

End While

datareader.Close()

并在执行此操作时出现此错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

1 个答案:

答案 0 :(得分:0)

问题是您使用SQLConnection打开Access数据库。这不行。

您需要SQLServer数据库或将OleDbConnection用于Access数据库。

以下是Microsoft KB文章,可帮助您连接到Access数据库: How To Retrieve and Display Records from an Access Database by Using ASP.NET, ADO.NET, and Visual Basic .NET以及CodeProject上的这个:http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners

Private Sub ReadRecords()
    Dim conn As OleDbConnection = Nothing
    Dim reader As OleDbDataReader = Nothing
    Try
        conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Elements.accdb"))
        conn.Open()

        Dim cmd As New OleDbCommand("Select Atomic Mass FROM Elements WHERE No =" & mol, conn)
        reader = cmd.ExecuteReader()    
        While reader.Read = True
        MessageBox.Show(reader.Item("Atomic Mass"))
        End While
    Finally

        If reader <> Nothing Then
            reader.Close()
        End If
        If conn <> Nothing Then
            conn.Close()
        End If
    End Try
End Sub