0

i want to insert to a sql table a string that might contain ' character.

what is my best way to do so ? should i insert a \ before the ' ? here's my command in a c# code:

SqlCommand myCommand = new SqlCommand(
    String.Format(
    "insert into ACTIVE.dbo.Workspaces_WsToRefile values({0},'{1}',getdate())", 
        folderId, 
        NewWorkspaceName), 
     myConnection);

where NewWorkspaceName might contain ' character, so the insert will cause an exception at the moment.

thanks in advanced, hadas.

4
  • 6
    You should use parameters in your query! Commented Aug 8, 2012 at 15:17
  • 3
    Beware of Little Bobby Tables! Commented Aug 8, 2012 at 15:18
  • 2
    What happens when NewWorkspaceName is "hi'); DELETE FROM Users; --" ? Commented Aug 8, 2012 at 15:19
  • i know for sure it won't be "hi'); DELETE FROM Users; --" , my only issue is with handeling ' on the string. Commented Aug 8, 2012 at 15:21

4 Answers 4

7

You should be using SqlParameter. http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx

    string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(@folderID, @newWorkSpace, @createDate)";

using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{

    SqlParameter param = new SqlParameter("@folderID", folderId);
    param.SqlDbType = SqlDbType.Int;
    cmd.Parameters.Add(param);
    .....
}
Sign up to request clarification or add additional context in comments.

Comments

3

You have only one option, forget everything else. Use Parametrized queries like this

SqlCommand myCommand = new SqlCommand("insert into ACTIVE.dbo.Workspaces_WsToRefile" + 
                                      " values(@id, @space, getDate()", myConnection);  
myCommand.Parameters.AddWithValue("@id", folderId);
myCommand.Parameters.AddWithValue("@space", NewWorkspaceName);
myCommand.ExecuteNonQuery();

folderID and NewWorkspaceName, are passed to the Sql Engine inside parameters.
This will take care of special characters like quotes.
But you gain another benefit using parametrized queries. You avoid Sql Injection Attacks

Comments

1
NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");

'' is a ' in sql

Comments

0

You can try this:

string stringToDatabase=Server.HtmlEncode("կҤїАͻBsdҤїА");

This saves 'stringToDatabase' in your database . Then while retreiving

string OriginalText=Server.HtmlDecode(stringFromDatabase);

1 Comment

It has to be WebUtility.HtmlEncode(stringFromDatabase) otherwise it does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.