`

数据源配置问题

阅读更多
采用数据源访问数据库


首先 加入相应的jar包 根据版本不同要加入 不同jar包 特别是Mysql

其次 配置数据源 可以在 项目中 META-INF 配置(被tomcat加载的) 也可以在Tomcat中配置 我这里就写 在第一个中配置的吧
      建个content.xm,注意了 用户名密码 都得写正确了 数据库驱动也得加正确了 数据库中数据库也要有下面配置中的数据库 例:test
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE XML>

<Context path="/guestbook" docBase="guestbook" debug="5" crossContext="true" reloadable="true">
    
<Resource name="jdbc/guestbook"
              auth
="Container"
              type
="javax.sql.DataSource" 
              maxActive
="5" 
              maxIdle
="5"
              maxWait
="10000" 
              driverClassName
="com.mysql.jdbc.Driver"
              url
="jdbc:mysql://localhost:3306/test"
              username
="root"
              password
="sa"
              testOnBorrow
="true" 
              testWhileIdle
="true" 
             
/>
</Context>
      先写个测试的吧,很多人直接用类 想写个连接数据库连接是否成功 但是这个是不行的 因为 jndi 的名称 获取不到 他是在tomcat启动时绑定的 这点要注意,如果真的要做的话也有个方法。现在先不写 以后再写吧 我们先写个 jsp测试页 如下testDS.jsp
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><%@ page import="java.sql.*,javax.sql.*,javax.naming.*" %>

<%
Connection conn 
= null;
try
  {
    Context ctx 
= new InitialContext(); 
    DataSource ds 
= (DataSource)ctx.lookup("java:comp/env/jdbc/guestbook");
    conn 
= ds.getConnection();
    System.out.println(
"connection pool connected !!");   
  } catch (NamingException e) {
    System.out.println(e.getMessage());
  } catch (SQLException e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
  }finally
  {
   conn.close();
 }
 
%>

看看是不是连接成功了呢 。。。

做这个 有时候 经常会出现一些奇奇怪怪的问题  但是不要着急  跟着 它反馈给我们的信息 GOOGLE 在GOOGLE 一切都变简单了
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics