⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connectionfactory.java

📁 关于servlet的很全的例子,对学习servlet很有帮助的,大家
💻 JAVA
字号:
package com.allanlxf.jdbc.util;

import java.sql.*;
import java.io.*;
import java.util.Properties;
import javax.naming.*;
import javax.sql.DataSource;

public class ConnectionFactory
{
    private static Properties config = new Properties();
    
    static
    {
        InputStream in = ConnectionFactory.class.getResourceAsStream("db-config.properties");
        if(in == null)
        {
            throw new ExceptionInInitializerError("no file:db-config.properties found error!");
        }        
        
        try
        {
            config.load(in);
            in.close();
        }catch(IOException e)
        {
            e.printStackTrace();
            throw new ExceptionInInitializerError("failed to load file!");
        }
    }
    
    public static Connection getDirectConnection() throws SQLException
    {
        try
        {
            String driverClassName = config.getProperty("driverClassName");
            String jdbcURL = config.getProperty("jdbcURL");
            String userName = config.getProperty("userName");
            String password = config.getProperty("password");
            
            Class.forName(driverClassName);
            return DriverManager.getConnection(jdbcURL, userName, password);
        }catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        }
    }
    
    public static Connection getJndiConnection() throws SQLException
    {
        try
        {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/" + config.getProperty("jndiName"));
            return ds.getConnection();
        }catch(Exception e)
        {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        }
    }
    
    public static Connection getConnection() throws SQLException
    {
        Connection con = null;
        if(config.getProperty("jndiName") != null)
        {
            try
            {
                con = getJndiConnection();
            }catch(Exception e)
            {
            }
            
            if(con == null)
            {
                con = getDirectConnection();
            }
        }else
        {
            con = getDirectConnection();
        }
        
        return con;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -