Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 392
  • Last Modified:

get total record from a table use cmd.ExecuteScalar()

Hi Expert,

I need get total record from a table

sqlScript="Select count(*) from table"

SqlCommand cmd = new SqlCommand(sqlScript, con);
 con.Open();


can I use cmd.ExecuteScalar() to return the number? If yes, how I can do it?

thanks in advance.
0
dshi15
Asked:
dshi15
  • 2
1 Solution
 
Paul JacksonCommented:
See the below code :

Dim SQLString As String = “SELECT Count(*) FROM tableName“
Dim yourDBConnection As New SqlConnection()
yourDBConnection.ConnectionString = yourConnectionString

 Dim cmd As New SqlCommand()
Dim recCount As Integer

yourDBConnection.Open()

cmd.Connection = yourDBConnection
 cmd.CommandText = SQLString 
 recCount = Integer.Parse(cmd.ExecuteScalar().ToString)

yourDBConnection.Close()

Open in new window

0
 
Paul JacksonCommented:
Converted to c# :

string SQLString = "SELECT Count(*) FROM tableName";
SqlConnection yourDBConnection = new SqlConnection();
yourDBConnection.ConnectionString = yourConnectionString;

SqlCommand cmd = new SqlCommand();
int recCount = 0;

yourDBConnection.Open();

cmd.Connection = yourDBConnection;
cmd.CommandText = SQLString;
recCount = int.Parse(cmd.ExecuteScalar().ToString);

yourDBConnection.Close();

Open in new window

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now