JDBC连接6步

 Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        servletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter out = servletResponse.getWriter();
        try {
            String url = "jdbc:mysql://localhost:3306/local?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
            String root = "root";
            String pwd = "123456";
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取链接
            con = DriverManager.getConnection(url, root, pwd);
            //操作数据库
            String sql = "select * from user";
            ps = con.prepareCall(sql);
            rs = ps.executeQuery();
            //获取结果集
            while (rs.next())
            {
                String id = rs.getString("id");
                String name = rs.getString("name");
                out.print(id+","+name+"<br>");
            }
        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }finally {
//            关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
posted @   走我们钓鱼去  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示