最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
简单的数据库连接工厂实现
时间:2008-01-12 编辑:简简单单 来源:一聚教程网
public class ConnectionFactory_JDBC1{
private static String url="jdbc:oracle:thin:@218.12.7.35:1521:myorcl";
private static String user="developer";
private static String password="developer";
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e){
throw new RuntimeException("无法加载数据库驱动!");
}
}
static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
public static void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
//没有必要处理
}
}
}
}
上面连接的是oracle数据库,当然这里用户名和密码以及url你也可以通过配置文件获得,虽然只有短短的几行
代码,对于新手,要完全理解也不是很容易的事,如果可能尽量使用JDBC2方法。
public class ConnectionFactory_JDBC2{
private static String dbName="jdbc/mydb";
private static DataSource ds;
static{
try{
Context ctx=new InitialContext();
ds = (DataSource)ctx.lookup(dbName);
}
catch(NamingException e){
throw new RuntimeException("无法获得数据源!");
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeConnection(Connection conn){
if (conn != null) {
-
上一个: 数据库链接资源该怎么优化
-
下一个: Tomcat配置SQLServer连接池
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24