ADO.net ASP.net如何填充数据表?

时间:2016-03-01 20:20:42

标签: asp.net vb.net ado.net

我是新手....如何正确填写此数据表?编辑器不喜欢这段代码,它让我在最后一次出现 conn Fill

之后出现曲线
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class WebForm4
Inherits System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim connstring As String
    connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\CompanyData.mdb"

    Dim conn As OleDbConnection
    conn = New OleDbConnection(connstring)

    conn.Open()

    Dim strSql As String
    strSql = "select * from Company"

    Dim cmd As SqlCommand
    cmd = New SqlCommand(strSql, conn)

    Dim da As SqlDataAdapter
    da = New SqlDataAdapter
    da.SelectCommand = cmd

    Dim dt As DataTable
    dt = New DataTable
    da.Fill(dt, "Company")

End Sub

1 个答案:

答案 0 :(得分:1)

您正在使用OleDb来使用MS-Access数据库。您应该使用OleDb类来完成所有事情。您创建了SqlCommandSqlDataAdapter,这些类适用于Sql Server,但不适用于OleDb

Dim connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\CompanyData.mdb"
Dim strSql = "select * from Company"

Using conn = New OleDbConnection(connstring)
Using cmd = New OleDbCommand(strSql, conn)
    conn.Open()

    Using da = New OleDbDataAdapter
       da.SelectCommand = cmd
       Dim dt = New DataTable
       da.Fill(dt, "Company")
   End Using
End Using

我更改了一些代码以显示如何使用Using Statement。此语句对于保持代码清洁非常重要,因为它会关闭并处理using行中声明的每个一次性对象。