簡而言之,您應該將通配符放在參數的值中,而不是放在CommandText中。即
不是: sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode%"
這樣的:
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode";
sqlCommand.Parameters.Add("@postcode", SqlDbType.NVarChar).Value = postCode + "%";
朗答案在這裏:
我回去,並剝奪我的代碼到要領,這樣我可以在這裏發佈,在做這件事時,我發現我在原始問題中嘗試的最後一種方法確實有效。在我的測試中一定是有問題的。所以這裏有一個總結,以飽滿的代碼一直運行:
原始動態sql,容易受到SQL注入:
//Dynamic sql works, returns 2 results as expected,
//but I want to use parameters to protect against sql injection
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE '"
+ postCode + "%'";
return Database.fGetDataSet(sqlCommand,
iiStartRecord,
iiMaxRecords,
"JOBVISIT");
使用參數首先嚐試給出一個錯誤:
//This syntax with a parameter gives me an error
//(note that I've added the NVarChar length as suggested:
//System.FormatException : @postcode : G20 -
//Input string was not in a correct format.
//at System.Data.SqlServerCe.SqlCeCommand.FillParameterDataBindings()
//at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommandText(IntPtr& pCursor,
// Boolean& isBaseTableCursor)
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode
+ '%'";
sqlCommand.Parameters.Add("@postcode",
SqlDbType.NVarChar,
10).Value = postCode;
return Database.fGetDataSet(sqlCommand, iiStartRecord, iiMaxRecords, "JOBVISIT");
第二種技術確實有效:
///This syntax with a parameter works, returns 2 results as expected
string postCode = "G20";
sqlCommand.CommandText = "SELECT * FROM JOB WHERE JOB_POSTCODE LIKE @postcode";
sqlCommand.Parameters.Add("@postcode", SqlDbType.NVarChar).Value = postCode
+ "%";
return Database.fGetDataSet(sqlCommand, iiStartRecord, iiMaxRecords, "JOBVISIT");
感謝所有的投入,對原誤導問題,對不起......
全面查詢: @ 「SELECT * FROM JOB WHERE DELETED = false AND JOB_POSTCODE LIKE'」+ isPostCode +'%'「 – Colin 2009-12-16 17:37:33