50,147
社区成员




public class ConnectUtil {
private static BasicDataSource dataSource = null;//创建空dbcp数据源对象
private static Logger logger = Logger.getLogger(ConnectUtil.class);//创建log4j日至工具类对象
private static Properties pros = new Properties();//创建数据库配置文件properties对象
/**
* ConnectUtil无参构造器
*/
public ConnectUtil() {
}
/**
* 实例化对象
*/
public static void init() {
if (dataSource != null) {
try {
dataSource.close();
} catch (Exception e) {
//
}
dataSource = null;
}
try {
pros.load(ConnectUtil.class
.getResourceAsStream("/db.properties"));
dataSource = (BasicDataSource) BasicDataSourceFactory
.createDataSource(pros);//这里的dataSource获取不到后面的连接对象。
} catch (Exception e) {
//
}
}
/**
* 创建数据库连接对象connection
*
* @return :Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn = null;
try {
if (dataSource == null) {
init();
}
if (dataSource != null) {
conn = dataSource.getConnection();
}
logger.info("--数据库连接成功---");
} catch (Exception e) {
// TODO: handle exception
logger.debug("--数据库连接失败---");
}
return conn;
}
/**
* 关闭连接对象
*
* @param conn
* 连接对象
* @param pstmt
* 预编译对象
* @param rs
* 结果集
*/
public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
logger.info("--ResultSet关闭成功---");
}
} catch (Exception e) {
logger.debug("--ResultSet关闭失败---");
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
logger.info("--PreparedStatement关闭成功---");
}
} catch (Exception e) {
logger.debug("--PreparedStatement关闭失败---");
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
logger.info("--Connection关闭成功---");
}
} catch (Exception e) {
logger.debug("--Connection关闭失败---");
e.printStackTrace();
}
}
}
}
## MySql
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.199:3306/doa?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
maxActive=30
maxIdle=10
maxWait=1000
removeAbandoned=false
removeAbandonedTimeout=120
#\u8C03\u53D6\u8FDE\u63A5\u65F6\u68C0\u67E5\u6709\u6548\u6027
testOnBorrow=true
testOnReturn=true
testWhileIdle=true
#\u9A8C\u8BC1\u8FDE\u63A5\u6709\u6548\u6027\u7684\u65B9\u5F0F\uFF0C\u8FD9\u6B65\u4E0D\u80FD\u7701
validationQuery=select 1 from dual
logAbandoned=true
timeBetweenEvictionRunsMillis=30000
minEvictableIdleTimeMillis=60000
public class Test {
public static void main(String[] args) {
try {
List<String> list = new ArrayList<String>();
Connection con = null;
PreparedStatement st = null;
ResultSet rs = null;
con = ConnectUtil.getConnection();
String sql = "SELECT public_url FROM public_number ";
st = con.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
list.add(rs.getString("public_url"));
}
System.out.println(list);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}