wpf 如何使用 sqlclient 类使用 vb.net 计算 sql 表中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30556976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:10:18  来源:igfitidea点击:

How to count number of rows in a sql table with vb.net using sqlclient class

sqlwpfvb.net

提问by Sonia Rehman

SELECT count(*) FROM table name 

this above code work fine in standalone sql table, but who can I do this simple task with in vb.net wpf project ?

上面的代码在独立的 sql 表中工作正常,但是我可以在 vb.net wpf 项目中与谁一起完成这个简单的任务?

采纳答案by Sachu

This is only a sample ..just check and try your own way.

这只是一个示例..只需检查并尝试自己的方式。

Sample:

样本:

Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;
                   User ID=UserName;Password=Password"
 sql = "Select count(*) from table"
 connection = New SqlConnection(connetionString)
 Try
   connection.Open()
   command = New SqlCommand(sql, connection)
   Dim sqlReader As SqlDataReader = command.ExecuteReader()
   While sqlReader.Read()
   MsgBox("Count =" & sqlReader.Item(0))
   End While
   sqlReader.Close()
   command.Dispose()
   connection.Close()
  Catch ex As Exception
  MsgBox("Can not open connection ! ")
 End Try

If your query return more than one values you can use SqlDataReader(), but if you are sure your query will return only a single value you can use ExecuteScalar()and if your query wont return any result, eg:- insert.it will insert value not return any data so we can use ExecuteNonQuery().The ExecuteNonQuery() will return a result which indicate is it successful or failure. If you want you can assign the same else no need.

如果您的查询返回多个值,您可以使用SqlDataReader(),但如果您确定您的查询将只返回一个您可以使用的值,ExecuteScalar()并且如果您的查询不会返回任何结果,例如:- insert.it 将插入值而不返回任何数据所以我们可以使用ExecuteNonQuery(). ExecuteNonQuery() 将返回一个结果,表明它是成功还是失败。如果你愿意,你可以分配相同的 else 没有必要。

回答by har07

Use SqlCommand.ExecuteScalar()method to execute query that return singular/scalar value (example based on that link) :

使用SqlCommand.ExecuteScalar()方法执行返回单数/标量值的查询(基于该链接的示例):

Dim count As Integer
Dim connString = "connection string to your database here"
Using conn As New SqlConnection(connString)
    Dim cmd As New SqlCommand("SELECT COUNT(*) FROM MyTable", conn)
    Try
        conn.Open()
        count = Convert.ToInt32(cmd.ExecuteScalar())
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try 
End Using