Skip to content

Instantly share code, notes, and snippets.

@bagaag
Last active December 22, 2015 01:08
Show Gist options
  • Save bagaag/6393884 to your computer and use it in GitHub Desktop.
Save bagaag/6393884 to your computer and use it in GitHub Desktop.
Parameterized string for safe sql queries, read from a sql.properties file in the classpath.
/*
* Parameterized string for safe sql queries, read from a sql.properties file
* Use: Statement.create("property.name")
* .set(":id", 123)
* .set(":date", new Date())
* .set(":name","O'Hara")
* .toString();
*/
package com.wiseley.util;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Matt Wiseley
*/
public class Statement {
private static java.util.Properties statements;
String sql;
private Statement(String name) {
if (statements==null) {
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("sql.properties");
statements = new java.util.Properties();
statements.load(is);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
sql = statements.getProperty(name);
}
private void testForName(String name) {
if (!sql.contains(name)) throw new RuntimeException(name + " not found");
}
public static Statement create(String name) {
return new Statement(name);
}
public Statement set(String name, String value) {
testForName(name);
value = value.replace("'", "''");
sql = sql.replace(name, value);
return this;
}
public Statement set(String name, int value) {
testForName(name);
sql = sql.replace(name, ""+value);
return this;
}
public Statement set(String name, long value) {
testForName(name);
sql = sql.replace(name, ""+value);
return this;
}
public Statement set(String name, Date value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String v = sdf.format(value);
set(name, v);
return this;
}
@Override
public String toString() {
return sql;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment