BlogJava 联系 聚合 管理  

Blog Stats

随笔档案

文章档案

Infernu的Google site


Infernus-JXH

1>. Properties:使用配置文件Properties,要求文件必须和.java在同一个package下,否则无法找到。配置文件如下:

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://192.168.0.13\:3306/myweb
username=root
password=lovejack

        构造器如下:

public class DbBean {
 private Connection con = null;
 private Properties props = new Properties();

 public DbBean() {
  try {
   props.load(this.getClass().getResourceAsStream(
     "dbconfig.properties"));
   Class.forName(props.getProperty("driver"));
   con = DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"), props.getProperty("password"));
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }

2>.ServletContext:配置局部xml文件,位于工程目录下WEB-INF文件夹内的web.xml,在其内增加字段:

  <context-param>
   <param-name>driver</param-name>
   <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <context-param>
   <param-name>url</param-name>
   <param-value>jdbc:mysql://192.168.0.13:3306/myweb</param-value>
  </context-param>
  <context-param>
   <param-name>username</param-name>
   <param-value>root</param-value>
  </context-param>
  <context-param>
   <param-name>password</param-name>
   <param-value>lovejack</param-value>
  </context-param>

构造器:

public DbBean(ServletContext context) {
  try {
   Class.forName(context.getInitParameter("driver"));
   con = DriverManager.getConnection(context.getInitParameter("url"), context.getInitParameter("username"), context.getInitParameter("password"));
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }

3>.ServletConfig:全局xml文件,位于tomcat\conf \web.xml, 在<servlet> </servlet>增加字段如下:

<init-param>
            <param-name>driver</param-name>
            <param-value>com.mysql.jdbc.Driver</param-value>
        </init-param>
        <init-param>
            <param-name>url</param-name>
            <param-value>jdbc\:mysql\://192.168.0.13\:3306/myweb</param-value>
        </init-param>
        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>password</param-name>
            <param-value>lovejack</param-value>
        </init-param>

构造器:

public void open(ServletConfig config) {
  try {
   Class.forName(config.getInitParameter("driver"));
     con = DriverManager.getConnection(config.getInitParameter("url"), config.getInitParameter("username"), config.getInitParameter("password"));
  }
  catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
  catch (SQLException e) {
   e.printStackTrace();
  }
 }

posted on 2009-10-13 17:26 Infernus 阅读(77) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: