admin管理员组文章数量:1794759
druid连接池连接sqlserver数据库
我在连接数据库时 ,控制台总是打印null,我总觉得是一些复杂的问题没弄到,最后通过调试知道其实是JdbcUtils中的getConnection()方法返回的null,而不是conn,我真是醉了。
数据库连接池的作用:
数据库连接池负责分配、管理释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏,提高数据库操作的性能。
package utils; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class JdbcUtils { private static DruidDataSource dataSource; static { Properties properties=new Properties(); InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); //读取jdbc.properties属性配置文件 try { properties.load(resourceAsStream);//从流中加载数据 try { dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);//创建数据库连接池 } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } /* 获取数据库连接池中的连接 */ public static Connection getConnection(){ Connection conn=null; try { conn=dataSource.getConnection(); } catch (SQLException throwable) { throwable.printStackTrace(); } return conn; } /* 关闭连接,放回数据库连接池 */ public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException throwable) { throwable.printStackTrace(); } } } }jdbc.properties配置文件在src 目录下
username=sa password=123456 url=jdbc:sqlserver://localhost:1433;DatabaseName=book driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver initialSize=5 maxActive=10 package test; import utils.JdbcUtils; import java.sql.*; public class JdbcUtilsTest { public static void main(String[] args) { Connection connection = null; connection = JdbcUtils.getConnection();//连接数据库 System.out.println(connection); String sql = "select * from users"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql);//创建PreparedStatement动态语句对象 ResultSet resultSet = preparedStatement.executeQuery();//返回结果集对象ResultSet while (resultSet.next()) {//处理返回结果 System.out.println(resultSet.getString(1)); System.out.println(resultSet.getString(2)); System.out.println(resultSet.getString(3)); System.out.println(resultSet.getString(4)); } preparedStatement.close();//关闭preparedStatement语句对象 } catch (SQLException throwables) { throwables.printStackTrace(); }finally { JdbcUtils.close(connection);//关闭数据库连接 } }用数据库连接池
只能获取10个,是因为配置文件中限制的连接的最大数量为10个。用完即时释放,获取多少连接都没问题。
版权声明:本文标题:druid连接池连接sqlserver数据库 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686656024a91260.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论