java sql where and,如何使用java.sql中where子句的动态计数执行mysql语句

博客讨论了如何通过使用SQL的IN子句优化从Java服务器发送ArrayList到MySQL服务器的查询,避免在循环中进行多次单一SELECT操作。提供了一个Java代码片段,展示了如何构建一个带有动态数量WHERE子句的SQL查询,并设置参数值。
摘要由CSDN通过智能技术生成

I have a jersey java server and a mysql server:

I send a POST with an ArrayList to the server. Then I want to do a select like ...where long OR long OR long....

Is there an elegant way to solve this problem and not to do always a single select in a for loop?

How can I form a sql-statement with dynamic count of where clauses?

Thank you very mutch.

解决方案

Instead of OR multiple times, you can use IN with the where clause in the SQL query.

You can read ArrayList object in a loop and set the where clause values.

JAVA code snippet:

int paramCount = list.size();

StringBuilder sqlSelect = new StringBuilder( 1024 );

sqlSelect.append( "select x,y,z from my_table " );

if( paramCount > 0 ) {

sqlSelect.append( "where long_column in ( " );

for( i = 0; i < paramCount; i++ ) {

sqlSelect.append( ( i > 0 ? ", ?" : "?" );

} // for each param

sqlSelect.append( " )" );

} // if list is not empty

// make the prepare statement (pst) with the above sql string

// ...

// now set the parameter values in the query

int paramIndex = 1;

if( paramCount > 0 ) {

for( i = 0; i < paramCount; i++ ) {

pst.setLong( paramIndex++, ( (Long)list.get( i ) ).longValue() );

} // for each param

} // if list is not empty

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值