Wednesday, May 23, 2007

List of question marks

Using only what a programming language standard API can provide, how do you generate a comma-separated list of question marks to be used as placeholders in a typical JDBC prepared statement? You know, the kind of "select * from tbl where code in (?, ?, ?, ?, ?)".

I tried to do it with the languages that I know. Say I want n question marks...

Java:
StringBuffer buf = new StringBuffer("?");
for (int i = 2; i <= n; i++) {
buf.append(", ?");
}
result = buf.toString();

Groovy:
def s = ('?' * n).toList().join(', ');

Ruby:
s = ('?' * n).split(//).join(', ')