2

From poking around in PreparedStatement, it appears that parameterizing SQL statements only allows the developer to specify positional arguments using ? and PreparedStatement.setX(index, value):

PreparedStatement statement = connection.prepareStatement("select * from something where id = ?;");
statement.setString(1, '5'); 

Is there a way to supply named parameters to prepared statements like this:

ParameterizedStatement statement = connection.parameterizeStatement(
    "select * from something where id = $id;");
statement.setString("id", "5");

Does something exist for this in Java?

1
  • Not in the JDBC api, but yes in JDBC wrapper libraries. Commented Dec 24, 2013 at 0:30

2 Answers 2

2

Not in the base JDK, but this sounds like the MyBatis SQL Builder Class.

For example,

// Anonymous inner class
public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("USER");
    WHERE("ID = ${id}");
  }}.toString();
}

// Builder / Fluent style
public String insertPersonSql() {
  String sql = new SQL()
    .INSERT_INTO("USER");
    .VALUES("ID, FIRST_NAME", "${id}, ${firstName}")
    .VALUES("LAST_NAME", "${lastName}")
    .toString(); 
  return sql;
}
Sign up to request clarification or add additional context in comments.

Comments

1

JPA queries can use named parameters, example:

EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x WHERE x.title = :titleParam and x.price > :priceParam");
q.setParameter("titleParam", "JDJ");
q.setParameter("priceParam", 5.0);
List<Magazine> results = (List<Magazine>) q.getResultList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.