Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to count number of records/rows in a returned dataset?

Posted on 2009-07-15
10
Medium Priority
?
1,149 Views
Last Modified: 2013-12-17

hello group,

Is the following piece of code a right way to count number of records which are returned after a SELECT has run?

ak
//code goes here
 
                    string strSQLStmt = "select * from MyTABLE where id='" + t.app_id + "'";
                    command.CommandText = strSQLStmt;
                    connection.Open();
                    Reader = command.ExecuteReader();
 
                    Reader.RecordsAffected();  //Is this a proper method?

Open in new window

0
Comment
Question by:akohan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 8

Expert Comment

by:RyanAndres
ID: 24864699
Use parameterized queries for security and to prevent sql injections.

Below is a snippet of something I'm currently working on.

once you fill 'result', you can get its result.Rows.Count value.
private readonly SqlConnection _connection;
 
public DataTable GetEmployees(int? employeeId, int? locationId)
 {
     SqlCommand cmd = _connection.CreateCommand();
     cmd.CommandText = "asp_get_scheduler_employee";
     cmd.CommandTimeout = 600;
     cmd.CommandType = CommandType.StoredProcedure;
 
     cmd.Parameters.Add("@Employee_UID", SqlDbType.Int).Value =
         (object) employeeId ?? DBNull.Value;
 
     DataTable result = new DataTable();
     SqlDataAdapter adapter = new SqlDataAdapter(cmd);
     adapter.Fill(result);
 
     return result;
 }

Open in new window

0
 
LVL 2

Expert Comment

by:d34thd34l34r
ID: 24864768
It is a property that will show you how many rows were updated, deleted or inserted however, to my knowledge, it is not meant for select queries as you are describing in you post.  I usually just use the example i posted below however, simply because its simple and you can read it like a book...
dr = cmd.ExecuteReader();
                int count = 0;
                while (dr.Read())
                {
                    this.userID = Convert.ToInt32(dr["UserID"]);
                    this.roleID = Convert.ToInt32(dr["RoleID"]);
                    this.name = dr["PersonName"].ToString();
                    this.franchiseID = Convert.ToInt32(dr["FranchiseID"]);
                    if (dr["FranchiseParentID"] != DBNull.Value) { this.parentFranchiseID = Convert.ToInt32(dr["FranchiseParentID"]); }
 
 
 
 
 
 
 
                    count++;
                }
 
                if (count > 0) { _isValid = true; } else { _isValid = false; }

Open in new window

0
 

Author Comment

by:akohan
ID: 24864993

Thanks for both your code but what should I do for cases like:

                    this.userID = Convert.ToInt32(dr["UserID"]);

I just want to run a SELECT command and get the number of records returned.






Regards

0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:akohan
ID: 24864997

As a matter of fact, I'm reading data from a text file and then trying to see if a record has the ID I have fetched from the text file. If true then update it if not then log it.

0
 
LVL 2

Expert Comment

by:d34thd34l34r
ID: 24865067
Well that changes things a bit if your reading from a text file.  Your example above showed you hitting a sql table.  If you want to get the record count from a query without running you could simply fill a dataset and the do something like this.dataset.tables[0].rows.count... If your having problems with a text file place your code here so i can see it and help you out a little easier.
0
 

Author Comment

by:akohan
ID: 24865465

OK, I'm using

while(Reader.Read()) iExists++;

to see if there is any record existing (it should be 1 always) so I'm fine as far as find a record but the problem is that I cannot update the record after finding it.

Any idea?

Thanks,


//
 
strSQLStmt1 = "";
strSQLStmt1 = "UPDATE table1 set myfield= '" + t.score.Trim().ToString() + "' WHERE Id = '" + t.applicant_id.Trim() + "' ";
Reader.Close();

Open in new window

0
 
LVL 6

Expert Comment

by:HarryNS
ID: 24867285
You can write a Stored Procedure and return the no. of records affected back to your application. It will be a return parameter of your SP.
0
 
LVL 2

Expert Comment

by:d34thd34l34r
ID: 24869011
I agree with HarryNS, you need to put everything in an stored procedure and run the following code i have provided in sql, return that to your .net code, then based on that create another SPROC to update the records.  See below for what your SPROCS should look like:


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE SelectCount_ByID
	@Id			int
AS
BEGIN
 
    Select
			count(1)
	From
			myTable
	Where
			tableID = @Id
END
GO
 
 
 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE UpdateTable_ByID
	@Id			int,
	@param1		char(10),
	@param2		char(2),
	@param3		bit
AS
BEGIN
 
    Update
			myTable
	Set
			param1 = @param1,
			param2 = @param2,
			param3 = @param3
	Where
			tableID = @Id
END
GO

Open in new window

0
 

Author Comment

by:akohan
ID: 24899446

Thanks but no it shouldn't be that complicate. I found that I was not supposed to use the code I used to.

In order to count the number of rows I'm using a variable  also instead of using   ExecuteReader()  I'm using ExecuteNonQuery() method which made it work.

Thank again for your help and time you took to explain it.


Regards,
ak
0
 

Accepted Solution

by:
akohan earned 0 total points
ID: 25028055

Thank you all for your help. since I didn't get the answer so I will be closing the thread so feel free to let me know if you don't agree with it.

Regards,
ak


p.s. I have posted the solution I'm using



                    int iRows = 0;
                    if (Reader.HasRows)
                    {
                        while (Reader.Read())
                        {
                            some code gone here
                            iRows++;
                        }
                    }
                    
                    //Here I will have total # of records.

Open in new window

0

Featured Post

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question