C# 如何计算访问数据库表的总行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18801235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:14:30  来源:igfitidea点击:

How to count total number of rows of an access database table?

c#visual-studio-2010ms-access

提问by Yogita Negi

string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();

回答by Damith

use

string cmdstr = "SELECT COUNT(*) FROM quant_level1";

With com.ExecuteScalar()

com.ExecuteScalar()

using(OleDbConnection conn = new OleDbConnection(constr))
using(OleDbCommand command = new OleDbCommand(cmdstr, conn)) 
{
    conn.Open();
    int count = (int)command.ExecuteScalar();
} 

ExecuteScalarreturns the first column of the first row in the result set returned by the query, here it give you row count.

ExecuteScalar返回查询返回的结果集中第一行的第一列,在这里它为您提供行数。

you can use OleDbDataReaderas you try in your code sample. but need to change the logic bit.

您可以OleDbDataReader在代码示例中尝试使用。但需要更改逻辑位。

using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("select * from quant_level1", con))
{
    con.Open();
    using (OleDbDataReader myReader = com.ExecuteReader())
    {
        DataTable dt = new DataTable();
        dt.Load(myReader);
        int count = dt.Rows.Count;
    }
}

Why you fail!

你为什么失败!

You have created data set but you haven't load data to dataset using your DataReader. So you will get zero row count at the end.

您已创建数据集,但尚未使用 DataReader 将数据加载到数据集。所以最后你会得到零行数。

回答by BRAHIM Kamel

You should do something like this:

你应该做这样的事情:

   Select count(*) from  quant_level1 

Change the command syntax executescalar to retrieve a single value

更改命令语法 executescalar 以检索单个值

CommandText = "SELECT COUNT(*) FROM region";   
Int32 count = (int32) ExecuteScalar(); 

Hope this can enlighten you a bit

希望这可以对你有所启发

回答by King King

Looks like that you want to fill your DataSetand count the rows later:

看起来您想DataSet稍后填充并计算行数:

DataSet data = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);  
da.Fill(data);
int i = data.Tables[0].Rows.Count;
Label2.Text = i.ToString();

If you just want to count the rows, you can change the query to SELECT COUNT(*) FROM quant_level1and get the return value like this:

如果您只想计算行数,您可以将查询更改为SELECT COUNT(*) FROM quant_level1并获取返回值,如下所示:

int i = (int) com.ExecuteScalar();
Label2.Text = i.ToString();