IDEA 使用Druid 链接数据库

冷不防 2023-10-03 18:32 23阅读 0赞

watermark_type_d3F5LXplbmhlaQ_shadow_50_text_Q1NETiBA55m95byA5rC06YO95pyJ5Lq655So_size_9_color_FFFFFF_t_70_g_se_x_16

首先去导入 druid 驱动和 数据库链接驱动 ,用maven的直接用就可以了

然后去配置 文件druid.properties

  1. driverClassName=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
  3. username=root
  4. password=123456
  5. initialSize=10
  6. maxActive=20
  7. maxWait=1000
  8. filters=wall

然后在主方法中使用

  1. // 创建properties 实体
  2. Properties pro = new Properties();
  3. // 加载配置文件
  4. pro.load(new FileInputStream("src/resource/druid.properties"));
  5. // 链接druid 数据池
  6. DataSource dataSource = createDataSource(pro);
  7. // 创建链接对象
  8. Connection conn = dataSource.getConnection();
  9. // 创建 发送SQL的对象
  10. Statement stmt = conn.createStatement();
  11. String sql = "select * from teachers";
  12. stmt.execute(sql);

当然也可以去写一个工具类,代码放在下面了

  1. public class Utils {
  2. private static DataSource ds ;
  3. static {
  4. Properties pro = new Properties();
  5. try {
  6. pro.load(new FileInputStream("src/resource/druid.properties"));
  7. ds = DruidDataSourceFactory.createDataSource(pro);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. /*获取链接*/
  13. public static Connection getConnection() throws SQLException {
  14. return ds.getConnection();
  15. }
  16. /**
  17. * 获取链接池方法
  18. */
  19. public static DataSource getDataSource(){
  20. return ds;
  21. }
  22. /*释放资源*/
  23. public static void close(PreparedStatement stmt,Connection conn){
  24. close(stmt,conn);
  25. }
  26. public static void close(ResultSet rs, Statement stmt, Connection conn) throws Exception {
  27. if (rs!=null){
  28. rs.close();
  29. }
  30. if (stmt!=null){
  31. stmt.close();
  32. }
  33. if(conn!=null){
  34. conn.close();
  35. }
  36. }
  37. }

发表评论

表情:
评论列表 (有 0 条评论,23人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Druid下载分享

    Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、J