开发者

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]
 ";

This is SqlCommand CommandText I will replace all st开发者_如何转开发ring that start with [ and end with ] before use command How Can I find parameter name beetwen [ and ] ? Do I have to use string.IndexOf (Sample,'[') ets. or Is there another void to make easy?


Don't do that - look into using SqlParameter instead to parametrize your queries, this is build in, i.e.:

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";
   //..
}


In addition to the possibility of using SqlParameter, you can define

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

and then obtain the command as

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

where id1 and id2 are your parameters.


No - you should String.Format method - see here: http://msdn.microsoft.com/en-us/library/system.string.format%28v=VS.100%29.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜