gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:38:49 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/17769858/

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