JDBC数据库连接管理类

package org.zhanghua.jspservlet.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

/**
* 数据库连接工具类
*
* @author ZhangHua
*
*/
public class DBConnection {
public static final String FILENAME = "/sql.properties";
private String driver;
private String url;
private String username;
private String password;

public DBConnection() throws Exception {
// 读取sql.properties属性文件
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(FILENAME));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driver);
}

/**
* 定义连接数据库的方法
*
* @return
* @throws Exception
*/
public Connection getConnection() throws Exception {
Connection connection = null;
connection = DriverManager.getConnection(url, username, password);
return connection;
}

/**
* 返回datasource方法 使用tomcat默认实现(DBCP),还可以使用c3p0的实现
*
* @return
*/
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}

public String getDriver() {
return driver;
}

public void setDriver(String driver) {
this.driver = driver;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public static void main(String[] args) throws Exception {
Connection connection = new DBConnection().getConnection();
System.out.println("连接的数据库:" + connection.getCatalog());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值