如何使用.net保存带撇号的字符串变量

时间:2015-05-17 13:06:59

标签: c# sql vb.net

我有这样的查询:

sql = "Select * From T_ExhibitorLocation 
        where F_ExhibitionCode='" & Cmb_Exhibition.SelectedValue.ToString & "' 
          and F_ExhibitorCode='" & Trim(Txt_ExhibitorID.Text) & "' 
          and F_Site='" & cmb_Site.SelectedValue.ToString &` "'"

有时我的F_site名称带有撇号, 例如 'Artist's Shell' 。所以这次我怎么能用撇号保存这个名字?提前谢谢

1 个答案:

答案 0 :(得分:2)

就像Pluntonix在他的评论中所说的总是试图避免以这种方式构建sql命令..如果可以的话,请采用以下方式

var command = new SqlCommand("Select * From T_ExhibitorLocation 
        where F_ExhibitionCode=@Cmbexhibition 
          and F_ExhibitorCode=@exhibitioncode
          and F_Site=@site");
SqlParameter param1  = new SqlParameter();
param1.ParameterName = "@Cmbexhibition";
param1.Value         = Cmb_Exhibition.SelectedValue.ToString();

SqlParameter param2  = new SqlParameter();
param2.ParameterName = "@exhibitioncode";
param2.Value         = Trim(Txt_ExhibitorID.Text);

SqlParameter param3  = new SqlParameter();
para3.ParameterName = "@site";
param3.Value         =cmb_Site.SelectedValue.ToString();

command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);

然后执行它。