Single quote handling in a SQL string

后端 未结 3 577
你的背包
你的背包 2020-12-14 18:09

I have an application where the values in the text field are sent to the database.

For example I have a form with one field (text box). When I press Ok button then t

相关标签:
3条回答
  • 2020-12-14 18:58

    Hope this will help you ...

    public static string DoQuotes(string sql)
        {
            if (sql == null)
                return "";
            else
                return sql.Replace("'", "''");
        }
    
    0 讨论(0)
  • 2020-12-14 19:08

    Use .Replace("'","''''")

    For example

    string name = txtName.Text.Replace("'","''''");
    

    Now name can be passed as a parameter in stored procedure etc.

    0 讨论(0)
  • 2020-12-14 19:11

    Don't ever build SQL statements like that, it's very unsafe (read this). Use parameters, i.e:

    var command = new SqlCommand("select * from person where firstname = @firstname");
    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@firstname";
    param.Value         = "testing12'3";
    command.Parameters.Add(param);
    
    0 讨论(0)
提交回复
热议问题