如何计算表中的行数? [英] How to count the no of rows in a table?

查看:108
本文介绍了如何计算表中的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何计算表中的行数?

How can we count the number of rows in a table?

string dbcnstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=path.mdf;Integrated Security=True;User Instance=True";
            
SqlConnection conn = new SqlConnection(dbcnstr);
conn.Open();
       
DataSet ds = new DataSet();
int c = ds.Tables["pic"].Rows.Count;
MessageBox.Show("pic table contains "+ c+" no of rows");
conn.Close();


这不能正常工作.


This doesn''t work properly. Please can any one help me?

推荐答案

似乎您是在指的是DataSet中尚不存在的表("pic") .您提供的代码将创建一个 empty 数据集,然后尝试访问一个根本不存在的特定表.

在尝试访问数据集的内容之前,您可能必须以某种方式填充该数据集.

我猜这就是您的意思,这无法正常工作".如果不是,请回复此答案,并提供您收到的任何错误消息或异常,或将其添加到原始问题中.谢谢.
It looks like you''re referring to a table that doesn''t exist in the DataSet yet ("pic"). The code you provided creates an empty DataSet, and then tries to access a specific table that simply isn''t there.

You''ll have to populate the DataSet somehow, perhaps by using a DataAdapter, before trying to access its contents.

I''m guessing that this is what you mean by "this doesn''t work properly." If not, please reply to this answer, and provide any error messages or exceptions you''re getting, or add them to your original question. Thanks.


好吧,您可以尝试在表中放入一些数据...



表已包含数据."

Well, you could try putting some data in the table...



"table is already containing data."

DataSet ds = new DataSet();
int c = ds.Tables["pic"].Rows.Count;

从什么时候开始?


您知道,与其使用DataSet读取整个表来获取行数,不如直接向数据库询问行数:

You know, instead of using a DataSet to read an entire table just to get the number of rows, one could ask the database for just the rowcount directly:

string dbcnstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=path.mdf;Integrated Security=True;User Instance=True";
            
SqlConnection conn = new SqlConnection(dbcnstr);
conn.Open();
       
SqlCommand getRowCount = new SqlCommand("SELECT COUNT(*) FROM pic", conn);
int c = (int)getRowCount.ExecuteScalar();

MessageBox.Show("pic table contains "+ c+" no of rows");
conn.Close();



当然,此代码假定您只想获取行数,而不要对DataSet中的数据做任何其他事情.如果不是这种情况,则忽略此答案:)



Of course, this code assumes that you only want to get the number of rows, and not do anything else with the data in your DataSet. If that''s not the case then just ignore this answer :)


这篇关于如何计算表中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆