insert into sql db a string that contain special character '

前端 未结 4 1760
抹茶落季
抹茶落季 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:17
    NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");
    

    '' is a ' in sql

    0 讨论(0)
  • 2020-12-22 13:19

    You can try this:

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

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

    string OriginalText=Server.HtmlDecode(stringFromDatabase);
    
    0 讨论(0)
  • 2020-12-22 13:20

    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);
        .....
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题