开发者

How to pass a string inside a query

I have to pass a string value inside a query...Here is my code

 string a = ConfigurationManager.AppSettings["var"];
SqlDataAdapter da = new SqlDataAdapter("select codesnippet from edk_custombrsnippet_开发者_如何学运维vw where partnerid = 'a'", con);
DataTable dt = new DataTable();
da.Fill(dt);

I got the value in string a..but i dont know how to pass that string in that query..Any suggestion?


Use a parameterized query, for example:

string a = ConfigurationManager.AppSettings["var"];
SqlDataAdapter da = new SqlDataAdapter(
  "select codesnippet from edk_custombrsnippet_vw where partnerid = @PartnerID",
  con);
da.SelectCommand.Parameters.AddWithValue("@PartnerId", a);
DataTable dt = new DataTable();
da.Fill(dt);

You should not embed the string value into the SQL itself - that opens you up to SQL injection attacks. Admittedly in this case it's not a user-provided value, but it's still better not to include it directly.

EDIT: I adapted this example from this MSDN page but it appears that SqlDataAdapter doesn't actually have a Parameters property as far as I can see. I've therefore adapted it to use SqlDataAdapter.SelectCommand.Parameters which I'd expect to work... but you may need to tweak it slightly.


Not that i recommend this approach in any way, you should at least use parameterised queries but to answer your question :

string a = ConfigurationManager.AppSettings["var"]; 
SqlDataAdapter da = new SqlDataAdapter(String.Format("select codesnippet from edk_custombrsnippet_vw      where partnerid = '{0}'",a), con); 
DataTable dt = new DataTable(); 
da.Fill(dt); 


I would recommend using paramters:

// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
    "select codesnippet from edk_custombrsnippet_vw where partnerid = @PartnerId", conn);

 string a = ConfigurationManager.AppSettings["var"];
// 2. define parameters used in command object
SqlParameter param  = new SqlParameter();
param.ParameterName = "@PartnerId";
param.Value         = a;

// 3. add new parameter to command object
cmd.Parameters.Add(param);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜