package com.aaa.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 工具类 获取数据库连接 释放资源等
*
* @author tuxianchao
*
*/
public class JDBCTools {
/**
* 获取数据库连接
*
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1. 准备连接数据库的 4 个字符串.
String driverClass = null;
String url = null;
String user = null;
String password = null;
// 1). 创建 Properties 对象
Properties properties = new Properties();
// 2). 获取 jdbc.properties 对应的输入流
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
// 3). 加载 2) 对应的输入流
properties.load(in);
// 4). 具体决定 user, password 等4 个字符串.
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
Class.forName(driverClass);
// 3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
return DriverManager.getConnection(url, user, password);
}
/**
* 释放数据库资源
*
* @param statement
* @param connection
* @param resultSet
*/
public static void release(Statement statement, Connection connection, ResultSet resultSet) {
if (resultSet != null) {//防止空指针异常
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testjdbc
user=root
password=root