使用C#检查Access数据库中是否存在记录

时间:2016-05-04 22:07:59

标签: c# ms-access exception try-catch nullreferenceexception

首先,我首先搜索了这个,然后发现这个问题已经回答:Previous Answer

我对此答案的问题是使用此方法会导致NullReferenceException。显然代码仍然可以使用try / catch块,但我一直都明白,故意使用Exception作为控制流的手段是糟糕的设计。有没有更好的方法呢?

为了清楚参数,我使用OleDbConnection和OleDbCommand来读/写Access 2010数据库(.accdb格式)。

以下是我目前使用上述答案方法的代码:

public bool ReadAccessDb(string filePath, string queryString, bool hasRecords)
    {
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data Source=" + filePath + ";" +
            @"User Id=;Password=;";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        using (OleDbCommand command = new OleDbCommand(queryString, connection))
        {
            try
            {
                connection.Open();

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

                //This works, but if no records exist it uses the Exception system to halt further action.  Look for better approach.
                if(count > 0)
                {
                    hasRecords = true;
                }
            }
            catch (System.Exception ex)
            {
            }
        }

        return hasRecords;
    }

2 个答案:

答案 0 :(得分:1)

您可以使用:

int count = command.ExecuteScalar() is DBNull ? 0 : Convert.ToInt32(command.ExecuteScalar());

或使用:

object obj = command.ExecuteScalar();
int count = obj is DBNull ? 0 : Convert.ToInt32(obj);

答案 1 :(得分:0)

我发布这个答案是因为这个问题有点含糊不清,而且(目前)接受的答案可以被愚弄了#34;如果存在行但SELECT语句返回的第一列恰好包含NULL。考虑测试表

CREATE TABLE MyTable (ID COUNTER PRIMARY KEY, NullableColumn INTEGER NULL)

INSERT INTO MyTable (NullableColumn) VALUES (NULL)

看起来像

ID  NullableColumn
--  --------------
 1          <NULL>

如果用于测试的SELECT语句是

string sql = "SELECT NullableColumn FROM MyTable WHERE ID=1";

然后是方法

static bool RecordExists(string queryString, OleDbConnection conn)
{
    bool rtn;
    using (var command = new OleDbCommand(queryString, conn))
    {
        object obj = command.ExecuteScalar();
        int count = obj is DBNull ? 0 : Convert.ToInt32(obj);
        rtn = (count != 0);
    }
    return rtn;
}

将返回False,而此方法

static bool RecordExists(string queryString, OleDbConnection conn)
{
    bool rtn;
    string rowCountString = String.Format("SELECT COUNT(*) AS n FROM ({0})", queryString);
    using (var command = new OleDbCommand(rowCountString, conn))
    {
        int count = (int)command.ExecuteScalar();
        rtn = (count != 0);

    }
    return rtn;
}

会返回True