简体   繁体   English

使用sql从数据库获取记录数

[英]Get the number of records from a database using sql

I am creating a test that will return the number of records in a table after I insert one record into it. 我正在创建一个测试,该测试将在向其中插入一条记录后返回表中的记录数。 The table in the database is initially empty so the count should return 1. This is the code I have written so far: 数据库中的表最初是空的,因此计数应返回1。这是我到目前为止编写的代码:

[TestMethod]
public void InsertBookIntoDb() {
    Database db = new Database();
    db.insertBooks("A", "C", "T");

    OleDbCommand countCommand = new OleDbCommand("SELECT COUNT(*) FROM Book", db.DbConnection);
    int count = countCommand.ExecuteNonQuery();

    Assert.AreEqual(1, count);
}

My db.insertBooks() method works correctly because I can manually open up the database and see that there is a new record. 我的db.insertBooks()方法可以正常工作,因为我可以手动打开数据库并查看是否有新记录。 After running this test, the count value is always 0 no matter how many records I insert into the database. 运行此测试后,无论我插入数据库中有多少条记录,计数值始终为0。 Is there a better way to get the total number of records? 有没有更好的方法来获取记录总数?

You need OleDbCommand.ExecuteScalar 您需要OleDbCommand.ExecuteScalar

Use the ExecuteScalar method to retrieve a single value, for example, an aggregate value, from a data source. 使用ExecuteScalar方法从数据源中检索单个值,例如聚合值。

 int count = (int) countCommand.ExecuteScalar();

you are using ExecuteNonQuery which is typically used for SQL statements without results (eg, UPDATE, INSERT, etc.). 您正在使用ExecuteNonQuery ,通常用于没有结果的SQL语句(例如UPDATE,INSERT等)。

we use ExecuteScalar typically when our query returns a single value. 我们通常在查询返回单个值时使用ExecuteScalar。 So just replace the ExecuteNonQuery' with the ExecuteScalar'. 因此,只需将ExecuteNonQuery' with the ExecuteScalar'。 It will work correctly. 它将正常工作。

    [TestMethod]
public void InsertBookIntoDb() {
    Database db = new Database();
    db.insertBooks("A", "C", "T");

    OleDbCommand countCommand = new OleDbCommand("SELECT COUNT(*) FROM Book", db.DbConnection);
    int count = (int) countCommand.ExecuteScalar();

    Assert.AreEqual(1, count);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM