时间:2021-07-01 10:21:17 帮助过:4人阅读
在DAO中获取连接实例
- <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> Connection getConnect(){
- Context initContext;
- Context envContext;
- Connection con </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
- </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
- initContext </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> InitialContext();
- envContext </span>= (Context) initContext.lookup("java:/comp/env"<span style="color: #000000;">);
- DataSource ds </span>= (DataSource) envContext.lookup("jdbc/PriceDB"<span style="color: #000000;">);
- con </span>=<span style="color: #000000;"> ds.getConnection();
- System.out.println(</span>"数据库连接成功"<span style="color: #000000;">);
- } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (NamingException e) {
- </span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated catch block</span>
- <span style="color: #000000;"> e.printStackTrace();
- } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (SQLException e) {
- </span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated catch block</span>
- <span style="color: #000000;"> e.printStackTrace();
- }
- </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> con;
- }</span>
【MySQL】JavaWeb项目中配置数据库的连接池
标签:try int nta std exception public 项目 except pre