0
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();
4

3 回答 3

3

利用

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

com.ExecuteScalar()

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

ExecuteScalar返回查询返回的结果集中第一行的第一列,这里它给你行数。

您可以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;
    }
}

你为什么失败!

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

于 2013-09-14T11:28:25.137 回答
1

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

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

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

int i = (int) com.ExecuteScalar();
Label2.Text = i.ToString();
于 2013-09-14T11:30:20.583 回答
0

你应该这样做:

   Select count(*) from  quant_level1 

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

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

希望这能给你一点启发

于 2013-09-14T11:30:18.610 回答