[英]how to pass comma seperated UUID in parameterized select query where IN clause
我有一個以UUID
作為鍵的表,並希望使用選擇查詢來獲取多行,因此查詢如下:
select * from table1 where ids in (:commaseperatedUUIDs); //DB is postgreSql
我在Java代碼中嘗試它,我有List<UUID>
,其中包含所有UUID,但是如果我使用字符串操作使它以逗號分隔,並在查詢中將字符串作為參數傳遞,則拋出SQL異常說明
operator does not exist: uuid = character varying
有什么線索嗎?
我也不了解Postgres,但是我可以在這里看到問題。 您的代碼求值是select * from table1 where ids in ('abc,bcd,dbc')
select * from table1 where ids in (abc,bcd,dbc)
中select * from table1 where ids in (abc,bcd,dbc)
而不是select * from table1 where ids in (abc,bcd,dbc)
中的select * from table1 where ids in (abc,bcd,dbc)
。
您可以做的是建立命令,例如:
sql = "select * from table1 where ids in (";
for (int i = 0; i < ids.length; i++)
if (i == 0)
sql += "?"
else
sql += ",?";
sql += ")";
PreparedStatement ps = connection.prepareStatement(sql);
for (int i = 0; i < ids.length; i++)
// replace the XXX with a valid type for UUID, I don't know what type to use
ps.setXXX(i+1, ids[i]);
由於您使用的是Spring,因此建議您使用NamedParameterJdbcTemplate ,因為它會自動將列表參數格式化為db可讀格式。
String sql ="select * from table1 where ids in (:commaseperatedUUIDs)"
List<Long> commaseparateduuids = new ArrayList<Long>();
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(myJdbcTemplate);
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("commaseparateduuids",commaseparateduuids);
namedTemplate.query(sql, parameters);
另外,建議某些dbms(例如Oracle)對IN
子句參數施加限制。 對於postgres來說不是這種情況,但是如果將來您要進行一些數據庫遷移,請考慮到這一點。
如果您使用的是Spring,則可以利用命名參數的支持,並將:commaseperatedUUIDs
的值作為java.util.List
傳遞。 參見文檔http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-in-clause
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.