[英]How to replace “[X]” in a string with a particular value for each X?
string Sample=@"
Select * from Table1 where Id =[MY Id]
and Column2=[MY Column2 Value]
";
這是SqlCommand CommandText。在使用命令之前,我將替換所有以[開頭和以]結尾的字符串。如何找到參數名稱beetwen [和]? 我是否必須使用string.IndexOf(Sample,'[')ets。 還是有另一個空白可以簡化?
不要這樣做-研究使用SqlParameter
來參數化您的查詢,這是內置的,即:
using(SqlCommand cmd = new SqlCommand("Select * from Table1 where Id = @id and Column2=@columnTwo", myConnection))
{
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt)).Value = someId;
cmd.Parameters.Add(new SqlParameter("@columnTwo", SqlDbType.NVarChar)).Value = "You name it";
//..
}
否-您應該使用String.Format
方法-參見此處: http : //msdn.microsoft.com/zh-cn/library/system.string.format%28v=VS.100%29.aspx
除了可以使用SqlParameter
,您還可以定義
string Sample=@"
Select * from Table1 where Id =[{0}]
and Column2=[{1}]
";
然后獲取命令為
string cmd = String.Format(Sample, id1, id2);
其中id1
和id2
是您的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.