我不明白为什么以下代码返回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
Dr.Read怎么可能是假的?
编辑:此问题已解决。该问题与globals.dif有关。首先对其进行了初始化,但随后在程序执行此功能之前更改了值,从而导致错误。我通过在getSectionLength函数中重新初始化dif来解决了它。
答案 0 :(得分:0)
我不知道您在何处获得此功能的模式,但它非常混乱。显然您正在尝试连接到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