tags:

views:

3574

answers:

5

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:

MessageFormat messageFormat = "insert into {0} values ( '{1}', '{2}', '{3}', {4} )";
Object[] args = { str0, str1, str2, str3, str4 };
String result = messageFormat.format(args);

I get this for the value of result:

"insert into <str0> values ( {1}, {2}, {3}, <str4> )"

As you can see, the problem is that any of the target locations that are enclosed by single quotes do not get replaced by arguments. I have tried using double single quotes like this: ''{1}'' and escaped characters like this: \'{1}\' but it still gives the same result.

edit: I forgot to mention that I also tried '''{1}'''. The result is: "insert into <str0> values ( '{1}', '{2}', '{3}', <str4> )". It is keeping the original quotes around but still not inserting the values.

How can I resolve this issue? For the record, I am using JDK 6u7.

A: 

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.

Bill James
Thanks. This is my current workaround but I'd prefer something a bit faster/cleaner.
TM
+2  A: 

Use triple single quote characters:

MessageFormat messageFormat = "insert into {0} values ( '''{1}''', '''{2}''', '''{3}''', '''{4}''' )";
Brian Duff
This just results in `"insert into <str0> values ( '{1}', '{2}', '{3}', <str4> )"`. So it has the single quotes now but the argument values still aren't being inserted.
TM
+6  A: 

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?

serg
I had tried this before, but it wasn't working. Something was screwed up with the build process... after a full clean -> rebuild, this method worked! *groan*. Thanks!
TM
You are welcome :)
serg
+4  A: 

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.

Aidos
I didn't know about this either, thanks!
TM