Escaping values in SQL queries (C# with SQL connector)

前端 未结 5 1818
囚心锁ツ
囚心锁ツ 2020-12-11 16:39

I know I can use the parameters, but what is the right way to escape string sequences? The query could be like this:

\"INSERT INTO records (ReferenceID,Name,         


        
相关标签:
5条回答
  • 2020-12-11 17:18

    If you need to perform database operations, such as creating tables, then you should use SQL Server Management Objects instead of executing SQL strings.

    For CRUD operations parameters is absolutely the only true path.

    UPDATE: It appears that the MySQL client library contains a helper method for this ill-advised task. You can call MySqlHelper.EscapeString(string).

    0 讨论(0)
  • 2020-12-11 17:20

    I think the only thing you need to do is value = value.Replace("'", "''")

    Of course you shouldn't do this, but you know that.

    Edit: Apparantly this is all wrong for MySQL. It should work for PostgreSQL, MS SQL and Oracle, though.

    0 讨论(0)
  • 2020-12-11 17:25

    The right way is to use parameters.

    "Just Say No" to trying to do the escaping yourself - it's far too easy to get wrong. Why do you think you'd want to escape them manually instead of using parameters?

    0 讨论(0)
  • 2020-12-11 17:38

    If you really, really, really need to do the escaping yourself (of which there is no sign in your example):

    string EncodeMySqlString(string value) {
       return value.Replace(@"\", @"\\").Replace("'", @"\'")
    }
    
    0 讨论(0)
  • 2020-12-11 17:42

    use commnd parameters instead. It takes care of escaping itself. It's the solution also against sql injections.

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