手记

java怎么从数据库中查询数据并输出

try {
            //这里的是MYSQL 举例
            //加载驱动 
            Class.forName("com.mysql.jdbc.Driver");
            //创建数据库连接
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
            //创建查询 “请求”
            PreparedStatement ps = con.prepareStatement("select * from user");
            //返回查询结果
            ResultSet rs = ps.executeQuery();
            //遍历结果
            while(rs.next()) {
                //假如 User 表中 有个 name 列
                System.out.println("name >> "+rs.getString("name"));
            }
            //关闭
            rs.close();
            ps.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

3人推荐
随时随地看视频
慕课网APP