我有我的sql查詢顯示使用變量「where」的字段。 我有我的變量從功能防止轉義字符串c#
串 empCode其價值是通過
這裏是我的代碼 「\\(!」
public List<int> GetSuccessAndFailedCountForTodayForAgent(string empCode)
{
var result = new List<int>();
string query = "SELECT (SELECT COUNT(*) FROM BusinessTransactions WHERE STATUS='Failed' AND ENTEREDDATE='" + DateTime.Now.Date.ToShortDateString() + "' AND AgentEmployeeCode='" + empCode + "') AS FAILED_COUNT, (SELECT COUNT(*) FROM BusinessTransactions WHERE STATUS='Completed' AND ENTEREDDATE='" + DateTime.Now.Date.ToShortDateString() + "' AND AgentEmployeeCode='" + empCode + "') AS SUCCESS_COUNT";
using (SqlConnection conn = new SqlConnection(asynchPaymentDBConnectionString))
{
conn.Open();
using (SqlCommand s = new SqlCommand(query, conn))
{
using (SqlDataReader reader = s.ExecuteReader())
{
try
{
if (reader.HasRows)
{
while (reader.Read())
{
result.Add(reader.GetInt32(0));
result.Add(reader.GetInt32(1));
}
}
}
catch (Exception ex)
{
//do something
}
}
}
}
return result;
}
在我的C#的結果變成0 - 0當我試圖直接sql服務器顯示結果2 - 0
字符串!\\(被視爲!\(
我如何使用我的字符串!\\(我的where子句?
編輯:
我嘗試使用參數補充說:
s.Parameters.Add("@EmployeeCode", SqlDbType.NVarChar, 16);
s.Parameters["@EmployeeCode"].Value = empCode;
還不行
嘗試參數化您的查詢。 –
您的代碼容易受到[SQL注入](http://www.w3schools.com/sql/sql_injection.asp)的影響。就像@FelixPamittan建議的那樣,你應該使用[parameters](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters%28v=vs.110%29.aspx)來構建您的查詢而不是串聯字符串。 –
鏈接爲重複http://stackoverflow.com/questions/5468425/how-do-parameterized-queries-help-against-sql-injection問題解釋什麼是SQL注入並顯示如何解決它(這也將解決您的問題您試圖破解) –