2011-09-24 48 views
0
string [email protected]" 
Select * from Table1 where Id =[MY Id] 
and Column2=[MY Column2 Value] 
"; 

這SqlCommand的CommandText中我將取代下手[和結束] 之前使用命令 所有的字符串我怎樣才能找到參數名beetwen [和]? 是否必須使用string.IndexOf(Sample,'[')ets。還是有另一個虛空讓人容易?如何用每個X的特定值替換字符串中的「[X]」?

+0

爲什麼一旦你知道值就不創建sql? –

+2

你爲什麼不能使用標準sql參數方法來完成這個任務的任何原因? –

回答

0

在除了使用SqlParameter的可能性,你可以定義

string [email protected]" 
Select * from Table1 where Id =[{0}] 
and Column2=[{1}] 
"; 

然後獲得命令爲

string cmd = String.Format(Sample, id1, id2); 

其中id1id2是你的參數。

+0

此方法對SQL注入打開。不要這樣做。 @ BrokenGlass的解決方案更好,因爲它使用參數化查詢。 –

+0

我同意,但OP將其制定爲一個字符串問題。我還引用了最安全的答案。 downvoting並不是真的有必要 – Andrea

7

別再這樣 - 考慮使用SqlParameter而不是參數化查詢中,這是建立,即:

using(SqlCommand cmd = new SqlCommand("Select * from Table1 where Id = @id and [email protected]", myConnection)) 
{ 
    cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt)).Value = someId; 
    cmd.Parameters.Add(new SqlParameter("@columnTwo", SqlDbType.NVarChar)).Value = "You name it"; 
    //.. 
} 
+1

+1 - 完全同意。您不希望受到SQL注入攻擊,也不必擔心包含「角色」的字符串。不要重新發明輪子。 –

+1

即使使用參數化查詢,您仍應驗證輸入數據。 –

+0

但我正在嘗試創建報告。因此,我必須在查詢 中找到參數,以便用戶插入值。 – YardimaIhtiyaciOlan

相關問題