通过查询显示错误传递单引号

时间:2016-01-19 14:41:21

标签: c# sql

foreach($data as $newInfo) {
        $session = Yii::$app->session;
        $session->open();
        $session['nombre'] = $newInfo['nombre'];
        $session['email'] = $newInfo['email'];

上面的查询显示错误,因为它缺少分号。 string query = "Select * from getLabelDetails where itemlookupCode='"+S"';"; 如何为此查询传递单引号?

4 个答案:

答案 0 :(得分:4)

对查询的简单更正是:

string query = "Select * from getLabelDetails where itemlookupCode='" + S +"'";

但它会导致SQL Injection,我希望您使用parameterized query来避免SQL Injection

您可以执行以下操作:

String sql = "Select * from getLabelDetails where itemlookupCode=@foo";
using (SqlConnection cn = new SqlConnection("Your connection string here")) 
   {
   using (SqlCommand cmd = new SqlCommand(sql, cn)) 
      {
        cmd.Parameters.Add("@foo", SqlDbType.VarChar, 50).Value = Baz;
        //execute command here
      }
   }

答案 1 :(得分:1)

您需要将单引号加倍。您的每个单引号都需要另一个单引号。

答案 2 :(得分:1)

你需要另一个报价。尝试:

string query = "Select * from getLabelDetails where itemlookupCode='" + S +"'";

从C#6.0开始,您还可以尝试字符串插值:

string query = $"Select * from getLabelDetails where itemlookupCode='{S}';"; 

答案 3 :(得分:-1)

var s = "something";
string query = "Select * from getLabelDetails where itemlookupCode=\'"+ s +"\';";