一:问题描述
当我们用模糊查询的时候 想向sql语句中的?赋值,这时会发现我们的sql语句一直报错
二:解决方法
package com.wyj.one;import com.wyj.pojo.Role;
import com.wyj.utils.JdbcutilsBydruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public class TextDBU02 {public static void main(String[] args) throws SQLException {//(1):获取连接Connection connection = JdbcutilsBydruid.getConnection();//(2):创建 queryRunner类(封装了sql的发送和执行以及返回的结果集)QueryRunner queryRunner = new QueryRunner();ArrayList<Object> list = new ArrayList<>();//(3):组织sqlString sql = "select count(1)\n" +"from smbms_user,\n" +" smbms_role\n" +"where smbms_user.userRole = smbms_role.id and username like ?";String username = "孙";list.add("%"+username+"%");Object[] params = list.toArray();//(4):执行返回的单行数据Object query = queryRunner.query(connection, sql, new ScalarHandler<>(),params);JdbcutilsBydruid.close(null,connection,null);System.out.println(query);}
}