木偶转转转 2021-12-30 10:13 采纳率: 100%
浏览 37
已结题

Java程序运行,查询记录集问题

Connectioncon=null;
PreparedStatementps=null;
ResultSetrs=null;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ph","root","123456");
ps=con.prepareStatement("select*fromt_userasuwhereu.namelike?andu.role='customer'");
ps.setString(1,"%"+customerName+"%");
语句各自是什么意思,大佬解释一下让孩子理解理解吧😭

  • 写回答

1条回答 默认 最新

  • 猫巳 Java领域优质创作者 2021-12-30 10:20
    关注
    // 连接对象
    Connectioncon con=null;//Connectioncon赋值为null
    // 预编译对象 PreparedStatement
    PreparedStatement ps=null;//PreparedStatementps赋值为null
    // 结果集
    ResultSet  rs=null;//ResultSetrs赋值为null
    
    Class.forName("com.mysql.jdbc.Driver");  //要求JVM查找并加载指定的com.mysql.jdbc.Driver类
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ph","root","123456"); //连接mysql数据库,后面的参数分别是地址,用户名,密码
    ps=con.prepareStatement("select * from t_user as u where u.name like ? and u.role='customer'"); //查询t_user表name包含?和role为customer的数据,?为通配符,下面替换成具体的参数
    ps.setString(1,"%"+customerName+"%"); //设置第一个?的值为"%"+customerName+"%",setString的意思是告诉ps这个参数是字符串类型。
    rs = ps.executeQuery(); //执行查询,接收返回结果
    // 遍历结果集
    while (rs .next()) {
    int id = rs .getInt("id");//获取id,id为字段名,下面类似
    String username = rs .getString("username");
    Date birthday = rs .getDate("birthday");
    System.out.println(id + "--" + username + "--" + birthday);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 4月30日
  • 已采纳回答 4月22日
  • 创建了问题 12月30日