数据存在,但我的程序显示“行/列没有数据”。

时间:2016-07-21 17:40:18

标签: c# ms-access oledb oledbcommand ms-access-2016

    private void recordFromTable()
    {
        String firstName = Environment.UserName.Split('.')[0];
        String lastName = Environment.UserName.Split('.')[1];
        String query = "SELECT LastUpdate FROM " + "EmployeeContact" + " WHERE EmployeeLastName='" + lastName + "' AND EmployeeFirstName='" + firstName + "'";
        try
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand command = new OleDbCommand(query, connection);
                connection.Open();
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        labelLastUpdated.Text = reader.GetString(0).Trim();
                    }
                }
            }
        } catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

抛出的异常是行/列没有数据。

我打开Access数据库并运行相同的查询(我的检查员在调试时显示),然后从数据库中返回一行。

Access中的所有字段都是“短文本”

2 个答案:

答案 0 :(得分:1)

很可能没有记录满足指定的WHERE条件,因此也没有满足所述异常。要验证运行此

SELECT COUNT(*) FROM 
EmployeeContact 
WHERE EmployeeLastName= lastName 
AND EmployeeFirstName=firstName;

您可能还想将查询更改为此

String query = "SELECT Nz(LastUpdate, 'NO DATA PRESENT') LastUpdate FROM " + "EmployeeContact" + " WHERE EmployeeLastName='" + lastName + "' AND EmployeeFirstName='" + firstName + "'";

答案 1 :(得分:1)

如果您确定数据存在,那么在我看来,您的firstName或lastName变量可能无法获得您认为或想要的值。