最近学习J2EE遇到的问题及解决方法(一)

我使用的J2EE开发环境是tomcat+eclipse+lomboz
问题一:怎样连接mysql数据库
步骤1:从mysql网站上下载jdbc驱动: http://dev.mysql.com/downloads/connector/j/3.1.html
              把驱动程序mysql-connector-java-3.1.13-bin.jar拷贝到tomcat安装路径/common/lib下
步骤2:在你工程中的META-INF目录下新建context.xml文件,内容为:
          
          
                              type="javax.sql.DataSource" username="你的数据库用户名" password="你的数据库密码"
                   driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/建立的数据库名"
                   maxActive="8" maxIdle="4"/>
          
           在你的工程中的web.xml配置文件中写入:
           
                       jdbc/BookDB
                       javax.sql.DataSource
                       Container
                       Shareable
           
步骤3:在你的java类中建立数据库连接,代码如下:
            try
            {
                     Context initCtx = new InitialContext();
                     Context envCtx = (Context) initCtx.lookup("java:comp/env");
                     DataSource ds = (DataSource) envCtx.lookup("在程序中注册的引用名");
                     con = ds.getConnection();
            }
            catch (Exception ex)
            {
                     throw new Exception("Couldn't open connection to database: "
                         + ex.getMessage());
            }

你可能感兴趣的:(J2EE)