import java.io.*;
import java.util.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class ConnectionFactory
{
/**
oracle 分页
select * from (
select a.*, ROWNUM rn from ( select * from user_info ) a
where ROWNUM<=40 )
where rn >=21
*/
private static Properties config = new Properties();
static
{
try
{
InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("dbconfig.properties");
config.load(in);
in.close();
}catch(IOException e)
{
e.printStackTrace();
throw new ExceptionInInitializerError(e.getMessage());
}
}
public static Connection getConnection()
{
if(config.getProperty("jndi-name") != null)
{
return getJndiConnection();
}
return getDirectConnection();
}
public static Connection getJndiConnection()
{
Connection con = null;
try
{
/**context.xml
数据源的配置
<Context>
<Resource name="jdbc/oracle" auth="Container" type="javax.sql.DataSource" maxActive="2" maxIdle="1" maxWait="-1"
username="openlab" password="open123" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@192.168.0.20:1521:tarena"/>
</Context
*/
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/" + config.getProperty("jndi-name"));
con = ds.getConnection();
}catch(Exception e)
{
e.printStackTrace();
}
return con;
}
public static Connection getDirectConnection()
{
Connection con = null;
try
{
Class.forName(config.getProperty("driver"));
con = DriverManager.getConnection(config.getProperty("dburl") ,config.getProperty("user"), config.getProperty("password"));
}catch(ClassNotFoundException cne)
{
cne.printStackTrace();
}catch(SQLException sqle)
{
sqle.printStackTrace();
}
return con;
}
public static void close(ResultSet rs, Statement st, Connection con)
{
try
{
rs.close();
}catch(Exception e)
{
}
try
{
st.close();
}catch(Exception e)
{
}
try
{
con.close();
}catch(Exception e)
{
}
}
public static void main(String[] args) throws Exception
{
Connection con = ConnectionFactory.getConnection();
System.out.println(con);
con.close();
}
}
posted on 2007-04-05 15:30
sunny 阅读(151)
评论(0) 编辑 收藏