JDBC中的命名參數是否有一個名為JDBC中,而不是那些位置參數,比如@name,@city在下面的ADO.NET查詢?select * from customers where name=@name and city = @city
3 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
JDBC不支持命名參數。除非你一定要使用普通的JDBC(這會導致痛苦,讓我告訴你),我建議使用Springs Excellent JDBCTemplate,它可以在沒有整個IoC容器的情況下使用。
NamedParameterJDBCTemplate支持命名參數,您可以像這樣使用它們:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("name", name); paramSource.addValue("city", city); jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
為了避免包含大型框架,我認為一個簡單的自制類可以做到這一點。
處理命名參數的類示例:
public class NamedParamStatement { public NamedParamStatement(Connection conn, String sql) throws SQLException { int pos; while((pos = sql.indexOf(":")) != -1) { int end = sql.substring(pos).indexOf(" "); if (end == -1) end = sql.length(); else end += pos; fields.add(sql.substring(pos+1,end)); sql = sql.substring(0, pos) + "?" + sql.substring(end); } prepStmt = conn.prepareStatement(sql); } public PreparedStatement getPreparedStatement() { return prepStmt; } public ResultSet executeQuery() throws SQLException { return prepStmt.executeQuery(); } public void close() throws SQLException { prepStmt.close(); } public void setInt(String name, int value) throws SQLException { prepStmt.setInt(getIndex(name), value); } private int getIndex(String name) { return fields.indexOf(name)+1; } private PreparedStatement prepStmt; private List<String> fields = new ArrayList<String>();}
調用類的示例:
String sql;sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";NamedParamStatement stmt = new NamedParamStatement(conn, sql);stmt.setInt("age", 35);stmt.setInt("id", 2);ResultSet rs = stmt.executeQuery();
請注意,上面的簡單示例不會處理兩次使用命名參數。它也不處理使用:引號內的符號。
添加回答
舉報
0/150
提交
取消