开发者

Do we have some placeholders in java for string as we have (?) in SQL prepared statement

Can i have placeholder for String java like we have in sql prepared statements?

Eg Conside that i have string St = "akkk ? la,ala ? " ,

now i want to set values of ? as i set it in sql prepared statement st.setStingValue(1,"akshay"); // do we have something like this? St.set开发者_开发百科StringValue(2,"anjaaa");


You can use String.format

String st = "akkk %s la,ala %s "; 
String result = String.format(st, "First Val", "Second Val");

Alternatively, you can use numeric positions

String st = "akkk %1$s la,ala %2$s "; 
String result = String.format(st, "First Val", "Second Val");


you can look at this Class MessageFormat


replaceFirst() is bad idea in this case - a first argument is expected to be a regex, if second arg contains sequences that are interpreted as regex processing directives eg. as group references (like '$') you will get an exception in trivial DB operation - depending on data passed to query.


Here is my variation.

 public class SimplePrepareStatement {
    String vars[];
    String query;

    public SimplePrepareStatement(String query) {
        int countVars = StringUtils.countMatches(query, "?");
        vars = new String[countVars];
        this.query = query.replaceAll("\\?", "%s");
    }

    public void setDouble(int i, Double arg0) {
        vars[i-1] = "'"+arg0+"'";
    }

    public void setString(int i, String arg0) {
        vars[i-1] = "'"+arg0+"'";
    }

    public void setObject(int i, String arg0) {
        vars[i-1] = arg0;
    }

    public String getSQL() {
        return String.format(query, vars);
    }
 }

Note! This is not for SQL use, possible SQLinjections, just similiar behavior.

   @Test
public void simplePrepareStatementTest() {
    SimplePrepareStatement st = new SimplePrepareStatement("abc ? abc ?");
    st.setString(1, "a");
    st.setString(2, "b");
    assertEquals("abc 'a' abc 'b'", st.getSQL());
    st.setObject(1, "obj");
    assertEquals("abc obj abc 'b'", st.getSQL());
}


you can use replaceFirst of the String to achieve the same effect.
read about it here : http://www.roseindia.net/java/string-examples/string-replacefirst.shtml

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜