您应该使用ExecuteScalar()
而不是ExecuteNonQuery()
因为您正在获取一个值。
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
为了正确编码
- 使用
using
声明进行正确的对象处理
- 使用
try-catch
块来正确处理异常
示例代码:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using