Single quote handling in a SQL string

2019-02-04 09:45发布

问题:

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 the content of the text field is inserted as a record into a table. I'm just trimming and extracting the text box's text into variable and passing it to my SQL string.

The problem is that whenever something like "It's" or "Friend's" the single quote is identified as the end of string. In Delphi I have seen something like QuotedString to avoide this. Any ideas from you?

回答1:

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);


回答2:

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

For example

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

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



回答3:

Hope this will help you ...

public static string DoQuotes(string sql)
    {
        if (sql == null)
            return "";
        else
            return sql.Replace("'", "''");
    }