簡體   English   中英

查詢以從MS Access數據庫獲取記錄數

[英]Query to get the count of records from MS Access database

我正在使用下面的代碼來獲取數據庫中存在的記錄數,但是不知何故。

拋出一個錯誤:

輸入的字符串格式不正確。

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)+”)“;

插入了單個qutations的正確代碼:

(OrderId ='“ + txtOrderNo.Text +”')“;

此錯誤來自正在構建SQL查詢的Convert.ToInt32 這意味着txtOrderNo.Textrow.Cells[1].Value包含非整數值,小數點或只是空字符串。 從MSDN文檔Convert.ToInt32在以下情況下將引發FormatException

值不包含可選符號,后跟數字序列(0到9)。

此外,您(嘗試)將數字轉換為Int32 ,然后將它們用作字符串,這是一個冗余操作。 一種簡單的解決方案是刪除轉換操作,但這仍然會使您留下無效的SQL語句,並且很容易受到SQL注入攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM