| url=jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false |
| username=root |
| password=123456 |
| driver=com.mysql.cj.jdbc.Driver |
| public class CustomDBUtil { |
| |
| private static String url; |
| |
| private static String username; |
| |
| private static String password; |
| |
| private static String driver; |
| |
| static { |
| try { |
| Properties properties = new Properties(); |
| properties.load(CustomDBUtil.class.getClassLoader().getResourceAsStream("db.properties")); |
| url = properties.getProperty("url"); |
| username = properties.getProperty("username"); |
| password = properties.getProperty("password"); |
| driver = properties.getProperty("driver"); |
| |
| Class.forName(driver); |
| }catch (Exception e){ |
| e.printStackTrace(); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public static Connection getConnection() throws Exception{ |
| Connection connection = DriverManager.getConnection(url,username,password); |
| return connection; |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static void close(ResultSet resultSet, PreparedStatement ps, Connection connection){ |
| try{ |
| |
| if(resultSet!=null){ |
| resultSet.close(); |
| } |
| if(ps!=null){ |
| ps.close(); |
| } |
| if(connection!=null){ |
| connection.close(); |
| } |
| }catch (SQLException e){ |
| throw new RuntimeException(); |
| } |
| } |
| |
| } |
| @WebServlet("/jdbc") |
| public class TestServlet extends HttpServlet { |
| |
| @Override |
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { |
| String idStr = req.getParameter("id"); |
| int id = Integer.parseInt(idStr); |
| try { |
| Connection connection = CustomDBUtil.getConnection(); |
| PreparedStatement ps = connection.prepareStatement("select * from user where id=?"); |
| ps.setInt(1,id); |
| ResultSet resultSet = ps.executeQuery(); |
| while (resultSet.next()){ |
| System.out.println("用户名称 name="+ resultSet.getString("username") + " 联系方式 wechat="+ resultSet.getString("wechat")); |
| } |
| CustomDBUtil.close(resultSet,ps,connection); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| } |
| } |
| |
| } |

| |
| http://localhost:8081/jdbc?id=1 |
| |
| |
| �û����� name=jack ��ϵ��ʽ wechat=xdclass6 |
| 数据库建⽴Connection⽐较耗时,频繁的创建和释放连接引起的⼤量性能开销 |
| 如果数据库连接得到重⽤,避免这些开销,也提⾼了系统稳定 |
| 数据库连接池在初始化过程中,往往已经创建了若⼲数据库连接置于池中备⽤,对于业务请求处理⽽⾔,直接利⽤现有可⽤连接,缩减了系统整体响应时间 |
| 统⼀的连接管理,避免数据库连接泄漏、超时占⽤等问题 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术