Insert text with single quotes in PostgreSQL

后端 未结 7 2144
北海茫月
北海茫月 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 12:08

    This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.

    You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.

    See Preventing SQL Injection in Java. Don't be Bobby's next victim.

    There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.

    There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.


    Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:

    insert into test values (1,'');DROP SCHEMA public;--');
    

    which breaks down to two statements and a comment that gets ignored:

    insert into test values (1,'');
    DROP SCHEMA public;
    --');
    

    Whoops, there goes your database.

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