我不明白为什么以下代码返回0而不是475:
Public Function getSectionLength(sectionUID As Integer) As Integer
Dim sectionLength As Integer = 0
Using dr As New DataReader(globals.dif)
Dim SQL As String = "SELECT dbo.SECTION_ATTRIBUTES.SECTION_LENGTH
FROM dbo.SECTION_ATTRIBUTES WHERE dbo.SECTION_ATTRIBUTES.SECTION_UID =
@sectionUid"
Dim paramList As New List(Of SqlClient.SqlParameter)
paramList.Add(New SqlClient.SqlParameter("@sectionUid",
sectionUID))
dr.ExecuteReader(SQL, paramList)
If dr.Read Then
sectionLength = dr("SECTION_LENGTH")
End If
End Using
Return sectionLength
End Function
以下是变量的值:
sectionUID = 38
当我在SSMS中运行SQL查询并交换@sectionUid为38时,我得到:
SECTION_LENGTH = 475
但
dr.Read = False
怎么可能会错误?
编辑:这已经解决了。这个问题与globals.dif有关。它首先被初始化,但是在程序命中该函数之前值已经改变,导致错误。我通过在getSectionLength函数中重新初始化dif来解决它。
我不知道你在哪里获得了这个功能的模式,但它非常混乱。显然您正在尝试连接到Sql Server数据库,但我没有在您的代码中看到任何连接。
首先,我们来看看您的代码。
'Good name for your function
Public Function getSectionLength(sectionUID As Integer) As Integer
Dim sectionLength As Integer = 0
'The DataReader constructor does take any arguments.
'You should be using an SqlDataReader
'Normally you do not need a New DataReader because .ExecuteReader returns a DataReader
'Good use of Using
Using dr As New DataReader(Globals.dif)
Dim SQL As String = "SELECT dbo.SECTION_ATTRIBUTES.SECTION_LENGTH
FROM dbo.SECTION_ATTRIBUTES WHERE dbo.SECTION_ATTRIBUTES.SECTION_UID =
@sectionUid"
'Commands provides its own collection called Parameters
Dim paramList As New List(Of SqlClient.SqlParameter)
paramList.Add(New SqlClient.SqlParameter("@sectionUid",sectionUID))
'The only argument that .ExecuteReader takes is a CommandBehavior enumeration
'.ExecutleReader won't do anything
dr.Execut1eReader(SQL, paramList)
If dr.Read Then
sectionLength = dr("SECTION_LENGTH")
End If
End Using
Return sectionLength
End Function
这可能是您代码的替代品。您需要将Imports System.Data.SqlClient
添加到文件的顶部。
Private Function GetSectionLength(SectionUID As Integer) As Integer
Dim sectionLength As Integer = 0
'Pass your connection string to the constructor of the connection
Using cn As New SqlConnection("Your connecion string")
'pass your sql statement and the connection directly to the constructor of the command
Using cmd As New SqlCommand("SELECT dbo.SECTION_ATTRIBUTES.SECTION_LENGTH
FROM dbo.SECTION_ATTRIBUTES
WHERE dbo.SECTION_ATTRIBUTES.SECTION_UID = @sectionUid", cn)
'Use the .Add method of the commands Parameters collection
cmd.Parameters.Add("@sectionUid", SqlDbType.Int).Value = SectionUID
'Open the connection at the last possible moment
cn.Open()
'.ExecuteScalar returns a single value, the first column of the first row of your query result
sectionLength = CInt(cmd.ExecuteScalar)
End Using 'Closes and disposes the command
End Using 'closes and disposes the connection
Return sectionLength
End Function