connectionfactory.java
来自「关于servlet监听器和过滤器的例子,大家如果有这方面的需求的话可以」· Java 代码 · 共 87 行
JAVA
87 行
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 + =
减小字号Ctrl + -
显示快捷键?