填充数据集时连接 属性 尚未初始化

Connection property has not been initialized when filling a DataSet

所以这是我的问题:

目前我正在尝试制作一份报告,显示第 1 班和第 2 班,多天...

所以如果他们 select 范围 6/02 - 6/04,我 运行 查询 3 次...一次是 6/02、6/03 和 6/ 04...他们也可以 select 换班,所以就是那些日期,但是第一班 4:30AM-4:30PM....

目前我有一个错误,当我试图将我的 queries/calls 放在 for 循环中时......我计算了两个日期的差异并将它们设置好,它只是我的连接字符串给了我错误:

如果图片不好看这里有错误的文字说明:

Server Error in '/mfgx_test' Application.

Fill: SelectCommand.Connection property has not been initialized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

Source Error:

Line 623: Dim dsTop1 As New DataSet Line 624: Dim daTop1 As New SqlDataAdapter(strSql, myCn1) Line 625:
daTop1.Fill(dsTop1) Line 626: Line 627: myCn1.Close()

Source File: C:\inetpub\wwwroot\mfgx_test\defectsbyround.aspx.vb
Line: 625

这让我相信我的连接字符串在我的 for 循环之外有问题......我的代码如下(虽然有点清理以便更容易阅读):

    Dim myCn1 As New SqlConnection
    myCn1.ConnectionString = "server=Blah;database=Blah;user id=Blah;password=Blah"
    myCn1.Open()

    For i = 0 To Session("DaysDiff")
        strSql = "Blah.Blah"
        Dim dsTop1 As New DataSet
        Dim daTop1 As New SqlDataAdapter(strSql, myCn1)
        daTop1.Fill(dsTop1)

        myCn1.Close()
        myCn1 = Nothing

        If dsTop1.Tables(0).Rows.Count > 0 Then
           spitout2(dsTop1)
        End If

           txtStartdate.Text = DateAdd("d",1,txtStartdate.Text)
           txtEnddate.Text = DateAdd("d",1,txtEnddate.Text)
   Next

那是因为您正在关闭循环内的连接,因此对于下一次迭代,不存在打开的连接,因此出现异常(见下文指出)

   myCn1.Close()
    myCn1 = Nothing

您应该在循环上下文之外声明 Datasettableadapter。您的代码应如下所示

Dim myCn1 As New SqlConnection
myCn1.ConnectionString = "server=Blah;database=Blah;user id=Blah;  password=Blah"
myCn1.Open()
Dim dsTop1 As New DataSet
Dim daTop1

For i = 0 To Session("DaysDiff")
    strSql = "Blah.Blah"
    daTop1 As New SqlDataAdapter(strSql, myCn1)
    daTop1.Fill(dsTop1)

 .......
Next

     myCn1.Close()
    myCn1 = Nothing

假设你想重用循环内的连接,在for循环外使用Using语句自动释放连接

Using myCn1 As New SqlConnection("server=Blah;database=Blah;user id=Blah;password=Blah")
    myCn1.Open()

    For i = 0 To Session("DaysDiff")
        strSql = "Blah.Blah"
        Dim dsTop1 As New DataSet
        Dim daTop1 As New SqlDataAdapter(strSql, myCn1)
        daTop1.Fill(dsTop1)

        If dsTop1.Tables(0).Rows.Count > 0 Then
           spitout2(dsTop1)
        End If

           txtStartdate.Text = DateAdd("d",1,txtStartdate.Text)
           txtEnddate.Text = DateAdd("d",1,txtEnddate.Text)
    Next

End Using

当达到End Using时,将调用SqlConnection.Dispose(),释放连接资源。