Get number of rows in a SQL Server table in VB.NET

busg9geu  于 2023-11-16  发布在  SQL Server
关注(0)|答案(3)|浏览(139)

There are 10 rows in primary_student_table .

When I execute the following code, the result was -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()

What's the problem in the above code?

iaqfqrcu

iaqfqrcu1#

You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.

count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())

For proper coding

  • use using statement for proper object disposal
  • use try-catch block to properly handle exceptions

Example Code:

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
czq61nw1

czq61nw12#

The solution is to replace

count = cmd.ExecuteNonQuery

with

count = cmd.ExecuteScalar

Like Robert Beaubien said in his comments

zbwhf8kr

zbwhf8kr3#

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

the value in count will be the number of rows in a table :) hope this helped

相关问题