查询以从 MS Access 数据库中获取记录数

Query to get the count of records from MS Access database

我正在使用下面的代码来获取数据库中存在的记录数,但不知何故它不起作用。

给我一个错误:

Input string was not in a correct format.

conn.Open();                       
OleDbCommand cmd1 = new OleDbCommand();
cmd1.CommandText = "select count(*) from Orders_Description where (ItemCode=" + Convert.ToInt32(row.Cells[1].Value) + ") and (OrderId=" + Convert.ToInt32(txtOrderNo.Text) + ")";
int recordExists = Convert.ToInt32(cmd1.ExecuteScalar());
if (recordExists > 0)
{
    //Insert command if record exists.
}

如果该字段的数据类型是等效的 nvarchar(非数字),则分配给 OrderId 的值前后需要单引号。

您的代码:

(OrderId=" + Convert.ToInt32(txtOrderNo.Text) + ")";

插入单引号的正确代码:

(OrderId='" + txtOrderNo.Text + "')";

此错误来自您构建 SQL 查询的 Convert.ToInt32。这意味着 txtOrderNo.Textrow.Cells[1].Value 包含非整数值、小数点或者只是空字符串。根据 Convert.ToInt32 的 MSDN 文档,在以下情况下将抛出 FormatException

value does not consist of an optional sign followed by a sequence of digits (0 through 9).

此外,您(尝试)将数字转换为 Int32,然后将它们用作字符串,这是一个多余的操作。简单的解决方案是删除转换操作,但这仍然会给您留下无效的 SQL 语句并且非常容易受到 SQL 注入攻击。