0
点赞
收藏
分享

微信扫一扫

SQL---JDBC基础6步

M4Y 2022-03-10 阅读 31
    Connection conn = null;
    Statement sta = null;
    ResultSet rs = null;
    try {
        //1、注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2、获取连接
       	conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","(密码)");
        //3、获取数据库连接对象
        sta = conn.createStatement();
        //4、执行SQL
        String sql = "select ename,sal from emp;";
        rs = sta.executeQuery(sql);
        //5.处理查询结果集
        while(rs.next()){
            String ename = rs.getString("ename");
            String sal = rs.getString("sal");
            System.out.println("名称:"+ename+",工资:"+sal);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        //释放资源
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (sta != null) {
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
举报

相关推荐

0 条评论