6

中有 10 行primary_student_table

当我执行以下代码时,结果为-1。

Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "

cmd = New SqlCommand(query, con)

count = cmd.ExecuteNonQuery
MsgBox(count)

con.Close()

上面的代码有什么问题?

4

3 回答 3

14

您应该使用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
于 2013-07-21T07:05:08.657 回答
5

解决方法是更换

count = cmd.ExecuteNonQuery

count = cmd.ExecuteScalar 

就像罗伯特·博比恩在他的评论中所说的那样

于 2013-10-06T01:44:11.293 回答
1
    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
    Dim READER As MySqlDataReader

    Try
        MysqlConn.Open()
        Dim Query As String

        Query = "Select * from dblms.accounts"
        COMMAND = New MySqlCommand(Query, MysqlConn)
        READER = COMMAND.ExecuteReader
        Dim count As Integer
        count = 0
        While READER.Read
            count = count + 1

        End While
      MysqlConn.Close()

    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        MysqlConn.Dispose()

    End Try

count 中的值将是表中的行数 :) 希望这有帮助

于 2015-01-21T03:31:39.203 回答