在数据库中创建users表并添加数据
使用JDBC工具类来查询数据,并把数据封装成一个User对象,然后通过uid来查询每个对象的内容。
使用工具类来查询所有对象,查询所有对象就要把对象都放到集合中,最后在遍历集合。
JavaBean类中根据users表信息,创建三个String私有成员变量,提供带参构造。
public class JDBCQueryDemo1 { public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); System.out.println("请输入您要查询的用户的uid:"); String uid = sc.nextLine(); User user = queryOneUserById(uid); if (user!=null){ System.out.println("您查询的用户存在:"+user); }else { System.out.println("您查询的用户不存在~~"); } System.out.println("--------"); List<User> list = queryAllUsers(); for (User u : list) { System.out.println(u); } } //根据uid查询uesr对象 public static User queryOneUserById(String uid) throws SQLException { //1.获取Connection连接对象 Connection con = JDBCUtil.getConnect(); //2.获取执行sql语句的Statement对象 Statement stmt = con.createStatement(); //3.执行查询操作 String sql = "select * from users where uid = ‘"+uid+"‘"; ResultSet rs = stmt.executeQuery(sql); //判断查询结果是否有数据 if (rs.next()){ //获取数据 String uid1 = rs.getString("uid"); String uname = rs.getString("uname"); String upass = rs.getString("upass"); User user = new User(uid1,uname,upass); return user; } //释放资源 JDBCUtil.release(con,stmt,rs); return null; } //查询所有uesr对象:把对象放在List集合中,返回List集合 public static List<User> queryAllUsers() throws SQLException { Connection con = JDBCUtil.getConnect(); Statement stmt = con.createStatement(); String sql = "select * from users"; ResultSet rs = stmt.executeQuery(sql); List<User> list = new ArrayList<>(); while (rs.next()){ String uid = rs.getString("uid"); String uname = rs.getString("uname"); String upass = rs.getString("upass"); User users = new User(uid,uname,upass); list.add(users); } //释放资源 JDBCUtil.release(con,stmt,rs); //返回List集合 return list; } }
运行结果: