user12207735
user12207735

Reputation:

Efficient way to concatenate multi-lines of SQL statements in Java?

Is there a way to efficiently concatenate multiple lines of strings in SQL statements in Java? As a developer who works with long SQL statements, I'm searching for a way to do this.

Upvotes: 0

Views: 3077

Answers (3)

Curiosa Globunznik
Curiosa Globunznik

Reputation: 3205

Nicer to look at may be that, though.

String pattern = 
        "INSERT INTO %s (%s,%s,%s) " +
        "VALUES (?,?,?)";
String query = String.format(pattern, "T", "C1", "C2", "C3");

Where T, C1 etc must not be taken from user input directly.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Yes, you can allocate a StringBuilder with enough room for the whole result, and then use its append to append the pieces, converting to string when you're done with toString:

StringBuilder sb = new StringBuilder(/*...number big enough for the whole thing...*/);
sb.append("SELECT [Foo], [Bar] FROM ");
sb.append(tableName); // **NOT** from a user, from internal logic
sb.append(" WHERE [X] = ?");
try (PreparedStatement ps = connection.prepareStatement(sb.toString())) {
    ps.setString(1, /*...*/); // This can be user-derived
    // ...
}

Be sure you don't put any user-derived information in the SQL via StringBuilder or other string-combining methods. That way lies SQL injection attacks... Let me introduce you to my friend Bobby:

enter image description here

Instead, for that part, use prepared statements and parameters as shown with [X] = ? and ps.setString (and comments) in the example above.

Upvotes: 3

Dorian Gray
Dorian Gray

Reputation: 2981

Apart from the above answers, JDK 13 introduces text blocks as a preview feature, which allows text blocks like that:

String message = """
    'The time has come,' the Walrus said,
    'To talk of many things:
    Of shoes -- and ships -- and sealing-wax --
    Of cabbages -- and kings --
    And why the sea is boiling hot --
    And whether pigs have wings.'
    """;

Note that this is a preview feature, which shall not be used in production yet. Has to be enabled with --enable-preview command line arg.

Upvotes: 1

Related Questions