gpt4 book ai didi

sql-server - 在 VB.NET 中获取 SQL Server 表中的行数

转载 作者:行者123 更新时间:2023-11-30 22:03:30 24 4
gpt4 key购买 nike

primary_student_table 中有 10 行。

当我执行下面的代码时,结果是-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()

上面的代码有什么问题?

最佳答案

您应该使用 ExecuteScalar() 而不是 ExecuteNonQuery() 因为您正在获取一个值。

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

正确编码

  • 使用 using 语句来正确处理对象
  • 使用try-catch block 来正确处理异常

示例代码:

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

关于sql-server - 在 VB.NET 中获取 SQL Server 表中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com