Java MessageFormat - How can I insert values between single quotes?

前端 未结 5 1813
渐次进展
渐次进展 2020-12-05 09:03

I\'m having a problem using the java.text.MessageFormat object.

I\'m trying to create SQL insert statements. The problem is, when I do something like this:

相关标签:
5条回答
  • 2020-12-05 09:45

    Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String. For example, pattern string "'{''}'" is interpreted as a sequence of '{ (start of quoting and a left curly brace), '' (a single quote), and }' (a right curly brace and end of quoting), not '{' and '}' (quoted left and right curly braces): representing string "{'}", not "{}".

    From: MessageFormat (Java Platform SE 8 )

    0 讨论(0)
  • 2020-12-05 09:46

    I just tried double quotes and it worked fine for me:

    MessageFormat messageFormat = new MessageFormat("insert into {0} values ( ''{1}'', ''{2}'', ''{3}'', {4} )");
    Object[] args = {"000", "111", "222","333","444","555"};
    String result = messageFormat.format(args);
    

    The result is:

    insert into 000 values ( '111', '222', '333', 444 )
    

    Is this what you need?

    0 讨论(0)
  • 2020-12-05 09:52

    Use triple single quote characters:

    MessageFormat messageFormat = "insert into {0} values ( '''{1}''', '''{2}''', '''{3}''', '''{4}''' )";
    
    0 讨论(0)
  • 2020-12-05 09:53

    First thing that came to mind was to change str1, str2, str3 to have the single quotes around them.

    Object[] args = { str0, "'" + str1 + "'", "'" + str2 + "'", "'" + str3 + "'", str4 };
    

    Then, of course, remove the single-quotes from your query string.

    0 讨论(0)
  • 2020-12-05 10:05

    Sorry if this is off the side, but it looks like you're trying to replicate the PreparedStatement that is already in JDBC.

    If you are trying to create SQL to run against a database then I suggest that you look at PreparedStatement, it already does what you're trying to do (with a slightly different syntax).

    Sorry if this isn't what you are doing, I just thought I would point it out.

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