Insert text with single quotes in PostgreSQL

后端 未结 7 2161
北海茫月
北海茫月 2020-11-21 11:28

I have a table test(id,name).

I need to insert values like: user\'s log, \'my user\', customer\'s.



        
7条回答
  •  灰色年华
    2020-11-21 11:54

    String literals

    Escaping single quotes ' by doubling them up -> '' is the standard way and works of course:

    'user's log'     -- incorrect syntax (unbalanced quote)
    'user''s log'

    In old versions or if you still run with standard_conforming_strings = off or, generally, if you prepend your string with E to declare Posix escape string syntax, you can also escape with the backslash \:

    E'user\'s log'
    

    Backslash itself is escaped with another backslash. But that's generally not preferable.
    If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:

    'escape '' with '''''
    $$escape ' with ''$$

    To further avoid confusion among dollar-quotes, add a unique token to each pair:

    $token$escape ' with ''$token$
    

    Which can be nested any number of levels:

    $token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$
    

    Pay attention if the $ character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.

    That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. @Craig's answer has more on that. More details:

    • SQL injection in Postgres functions vs prepared queries

    Values inside Postgres

    When dealing with values inside the database, there are a couple of useful functions to quote strings properly:

    • quote_literal() or quote_nullable() - the latter outputs the string NULL for null input. (There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.)
    • format() with the format specifier %L is equivalent to quote_nullable().
      Like: format('%L', string_var)
    • concat() or concat_ws() are typically no good as those do not escape nested single quotes and backslashes.

提交回复
热议问题