最底层JDBC实现代码

 public void testJDBC(){
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            //1加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2创建连接
            conn = DriverManager.getConnection("jdbc:mysql:///web17","root","123456");
            //3编写sql语句
            String sql = "select * from user where username = ?";
            //4预编译sql
            psmt = conn.prepareStatement(sql);
            //5设置参数值
            psmt.setString(1,"sun");
            //6执行sql
            rs= psmt.executeQuery();
            //7遍历结果集
            while (rs.next()){
                //8得到返回的结果集

                String username = rs.getString("username");
                String password = rs.getString("password");
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                System.out.println(user);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                psmt.close();
                conn.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

猜你喜欢

转载自blog.csdn.net/sunaxp/article/details/81062184