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 ?
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 ?
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.
Use SqlCommand.ExecuteScalar() method to execute query that return singular/scalar value (example based on that link) :
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