且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算表中的行数?

更新时间:2023-02-06 10:30:16

似乎您是在指的是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 :)