insert into sql db a string that contain special character '

前端 未结 4 1777
抹茶落季
抹茶落季 2020-12-22 12:40

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 i

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 13:25

    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

提交回复
热议问题