开发者社区> 问答> 正文

mysql的模糊查询语句怎么写?:报错

代码如下,我想在学生表中模糊查询名字。
报错
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).


public class SerchDao {

public List<Student> serch(String name) throws ClassNotFoundException, SQLException{

ArrayList<Student> list=new ArrayList<Student>();

//得到数据库的连接

Connection conn=MysqlConn.getConn();

//创建sql语句

String sql="select * from student where name like '?%'";

//创建执行对象

PreparedStatement prep=conn.prepareStatement(sql);

//设置占位符参数

prep.setString(1, name);

ResultSet rs=prep.executeQuery();

while(rs.next()){

int idDB=Integer.parseInt(rs.getObject("id").toString());

String nameDB=rs.getObject("name").toString();

int ageDB=Integer.parseInt(rs.getObject("age").toString());

String sexDB=rs.getObject("sex").toString();

//保存对象的信息

Student stu=new Student();

stu.setId(idDB);

stu.setName(nameDB);

stu.setAge(ageDB);

stu.setSex(sexDB);

list.add(stu);

}

return list;

}

}

展开
收起
kun坤 2020-06-09 11:04:26 536 0
1 条回答
写回答
取消 提交回答
  • Parameter index out of range (1 > number of parameters, which is 0).把prep.setString(1, name); 改成prep.setString(0, name); 试试######回复 @supermanxkq : 可以试试3楼说的,不过你这样大量使用模糊查询,性能不高######不行啊..######不行###### select * from student where name like '?%'
    字符串内部的问号mysql不会认为他是占位参数,改成
    select * from student where name like ?
    参数用prep.setString(1, name + “%”); 最好对name做个预检查不要出现通配符

    2020-06-09 11:04:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像