【问题标题】:Get the number of records from a database using sql使用sql从数据库中获取记录数
【发布时间】:2013-11-18 18:06:36
【问题描述】:

我正在创建一个测试,该测试将在我向其中插入一条记录后返回表中的记录数。数据库中的表最初是空的,所以计数应该返回 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);
}

我的 db.insertBooks() 方法工作正常,因为我可以手动打开数据库并看到有一条新记录。运行此测试后,无论我向数据库中插入多少条记录,计数值始终为 0。有没有更好的方法来获取记录总数?

【问题讨论】:

    标签: c# sql sql-server database unit-testing


    【解决方案1】:

    你需要OleDbCommand.ExecuteScalar

    使用 ExecuteScalar 方法检索单个值,例如, 来自数据源的聚合值。

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

    【讨论】:

    • 我还必须使用 Thread.Sleep(1000) 才能正确执行
    • @user2246631,不太清楚你为什么需要它,你的代码似乎没有在单独的线程中执行它。
    【解决方案2】:

    您正在使用ExecuteNonQuery,它通常用于没有结果的 SQL 语句(例如,UPDATE、INSERT 等)。

    我们通常在查询返回单个值时使用 ExecuteScalar。 所以只需替换ExecuteNonQuery' with theExecuteScalar'。它将正常工作。

        [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);
    }
    

    【讨论】:

    • ExecuteScalar 返回object,需要转换/转换为int,否则会报错
    猜你喜欢
    • 2011-05-29
    • 2023-01-07
    • 1970-01-01
    • 2011-08-18
    • 2013-01-27
    • 2015-11-20
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多