试图查询数据库

时间:2010-10-28 20:36:57

标签: vb.net

我在使用数据库中的值填充集合类时遇到了一些问题。每次我循环遍历WHILE DR.READ循环中的记录时,最后一条记录会写入集合中的所有其他项目。我的returnVal集合有几个相同的项目,尽管循环显示每个单独的记录被添加到returnVal。谢谢你的帮助。

Public Shared Function getStuff(ByVal sb As StringBuilder) As System.Collections.Generic.List(Of Minutes)

    Dim returnVal As New System.Collections.Generic.List(Of Minutes)

    Dim conn As New SqlConnection

    Dim cmd As New SqlCommand

    Dim dr As SqlDataReader

    conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    cmd.Connection = conn
    cmd.CommandText = sb.ToString

    Try
        conn.Open()
        dr = cmd.ExecuteReader

        While dr.Read
            Dim _minutes As New Minutes
            _minutes.Minutes = dr("minutes")
            _minutes.MinutesId = dr("minutesId")
            returnVal.Add(_minutes)
        End While


    Catch ex As Exception
        Dim _minutes As New Minutes
        _minutes.Minutes = ex.ToString
        _minutes.MinutesId = 0
        returnVal.Add(_minutes)
    End Try
    conn.Close()
    Return returnVal

End Function

这是我的会议纪要

Imports Microsoft.VisualBasic

Public Class Minutes

    Private Shared _minutesId As Integer

    Private Shared _minutes As String


    Public Property MinutesId() As Integer
        Get
            Return _minutesId
        End Get
        Set(ByVal value As Integer)
            _minutesId = value
        End Set
    End Property
    Public Property Minutes() As String
        Get
            Return _minutes
        End Get
        Set(ByVal value As String)
            _minutes = value
        End Set
    End Property
    Public Shared Function getStuff(ByVal sb As StringBuilder) As System.Collections.Generic.List(Of Minutes)
        Return MinutesDA.getStuff(sb)
    End Function
    Public Shared Function modify(ByVal sb As StringBuilder) As String
        Return MinutesDA.modify(sb)
    End Function
    Public Shared Property Id() As Integer
        Get
            Return MinutesDA.Id
        End Get
        Set(ByVal value As Integer)
            MinutesDA.Id = value
        End Set
    End Property
    Public Shared Property Index() As Integer
        Get
            Return MinutesDA.Index
        End Get
        Set(ByVal value As Integer)
            MinutesDA.Index = value
        End Set
    End Property
End Class

2 个答案:

答案 0 :(得分:0)

要确认您获得新值或相同值,请尝试以下操作:

   Dim i as Integer
   i = 0
   While dr.Read

        Dim _minutes As New Minutes
        _minutes.Minutes = dr("minutes")
        ' _minutes.MinutesId = dr("minutesId")
        _minutes.MinutesId = i
        i = i + 1
        returnVal.Add(_minutes)
    End While

在此之后,您可以看到MinuteId是否不同。

<强> N.B。在VB6中,您必须在循环结束时将_minutes设置为Nothing以获取新实例。但是我不会想到在VB.NET中会出现这种情况

答案 1 :(得分:0)

问题是Minutes类中的字段是共享的。所有类的实例都将共享一个字段实例。从字段中删除“共享”:

Private _minutesId As Integer

Private _minutes As String

这将分别存储每个实例的值