开发者

How to generate String "elegantly" in Java?

开发者 https://www.devze.com 2023-03-01 04:37 出处:网络
I want to generate a string such as sql command: \"INSERT INTO xxx VALUES(XXX, XXX, XXX)\" currently I use StringBuilder and some String 开发者_开发问答constant like \"INSERT INTO\" to concatenate

I want to generate a string such as sql command:

   "INSERT INTO xxx VALUES(XXX, XXX, XXX)"

currently I use StringBuilder and some String 开发者_开发问答constant like "INSERT INTO" to concatenate input String parameters for the table name and inserted values.

However, other than performance issue, this plain concatenation looks not elegant. Is there any other way of doing this?

In my opinion, JDBC's prepared statement is one good example of such a "command template":

PreparedStatement pstmt=connection.createPreparedStatement("INSERT INTO ? VALUES(?,?,?)");

then you can set the table name and inserted value.

pstmt.setString(1,"tableA");
pstmt.setInt(2, 100);
...

However, I can not use prepared statement, since what I want is just String...

And someone give me some hint to use java.util.Regex or JavaCC to produce the String. But as far as I can see, whatever is chosen for some code elegancy issue, Java String must be generated by something like StringBuilder, right???


You could use String.format():

String.format("insert into %s values('%s', '%s', '%s')", "user", "user123", "pass123", "yellow");

It's worth noting though, that any of these "string building" techniques leave you vulnerable to SQL injection attacks. You should really use JDBC parameterised queries wherever possible.

Edited to add quotes around strings.


Maybe you are looking for java.text.MessageFormat

 int planet = 7;
 String event = "a disturbance in the Force";

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);


Have you tried just using '+' ?

String sql = "INSERT INTO " + table
           +" VALUES(" + value1 + ", " + value2 + ", " = value3+")";


Given the variety of other answers and none of them met your approval, perhaps you should accept that the actual String generation (sans JPA, PreparedStatement, etc.) is going to be fairly inelegant and create a utility class with static sql generators.

edit Showing an example of how I'd go about this if a pre-existing class such as PreparedStatement weren't an option. It's not the most elegant, but it does what it's supposed to (assuming I typed it all in correctly).

public class SQLUtil {
    public static String generateInsertSQL(String tableName, List<CustomParameter> parmList){
        StringBuilder sb = new Stringbuilder();
        sb.append("insert into ");
        sb.append(tableName);
        sb.append(" values (");
        for (int i = 0; i < parmList.size(); i++){
            customParameter parm = parmList.get(i);
            switch (parm.getType()) { // enum with your desired sql types
                case ParmTypes.String:
                    sb.append("'");
                    sb.append(StringEscapeUtils.escapeSql(String.valueOf(parm.getValue())));
                    sb.append("'");
                    break;
                case ParmTypes.Integer:
                    sb.append(Integer.valueOf(parm.getValue()));
                    break;
            }
            if (i < parmList.size() - 1) sb.append(",");
        }
        sb.append(")");
        return sb.toString();
    }
}

This way, your business code will remain relatively elegant and you can play around with the SQL String generation to your heart's content. You can also use this to "guarantee" all your inserts are protected against such attacks as SQL injection.


Use StringTemplate (http://www.stringtemplate.org/) maybe a good choice:

This looks better, right?

StringTemplate insert = new StringTemplate("INSERT $table$ VALUES ($value; separator=\",\"$)");
insert.setAttribute("table", "aTable");
String[] values = {"1", "1", "'aaa'", "'bbb'"};
for(int i = 0;i < values.length;i++){   
  insert.setAttribute("value", values[i]);  
}
System.out.println(insert.toString());
0

精彩评论

暂无评论...
验证码 换一张
取 消