JDBC工具类:JDBCUtils
- 目的:简化书写
分析:
-
1,注册驱动抽取
-
2,抽取一个方法获取连接对象
需求:不想传递参数(麻烦),还得保证工具的通用性 解决:配置文件 jdbc.properties url=.... user=.... password=....
-
3,抽取一个方法释放资源
工具类:
public class JDBCUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
/**
* 文件的读取,只需要读取一次即可得到这些值,使用静态代码块
*/
static {
try {
//读取资源文件
//1,Properties集合类
Properties properties = new Properties();
//获取src路径下的文件---->ClassLoader 类加载器
ClassLoader classLoader=JDBCUtils.class.getClassLoader();
URL res=classLoader.getResource("JdbcUtils.properties");
String path = res.getPath();
//2,加载文件
properties.load(new FileInputStream(path));
//3,获取属性,赋值
url = properties.getProperty("url");
password = properties.getProperty("password");
user = properties.getProperty("user");
driver = properties.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭资源
*/
public static void close(ResultSet rs,Statement statement, Connection connection){
if(rs!=null){
try {
rs.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();
}
}
}
}
配置文件:
url=jdbc:mysql:///school
user=root
password=root
driver=com.mysql.jdbc.Driver
测试代码:
public class JdbcTest4 {
public static void main(String[] args){
List<emp> all = new JdbcTest4().findAll();
System.out.println(all);
}
public List<emp> findAll() {
Connection connection = null;
Statement statement = null;
List<emp> list=null;
ResultSet rs=null;
try {
//1,导入驱动jar包
//2,注册驱动
// Class.forName("com.mysql.jdbc.Driver");
// //3,获取数据库
// connection = DriverManager.getConnection("jdbc:mysql:///school", "root", "root");
connection=JDBCUtils.getConnection();
//4,定义sql语句
String sql = "select * from bank_one";
//5,获取执行sql的对象 Statement
statement = connection.createStatement();
//6,执行方法
rs = statement.executeQuery(sql);
//7,处理结果
emp e = null;
list = new ArrayList<emp>();
while (rs.next()) {
String name = rs.getString("name");
int account = rs.getInt("account");
e = new emp();
e.setName(name);
e.setAccount(account);
list.add(e);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs,statement,connection);
}
return list;
}
}
数据封装:
public class emp {
private String name;
private int account;
@Override
public String toString() {
return "emp{" +
"name='" + name + '\'' +
", account=" + account +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAccount() {
return account;
}
public void setAccount(int account) {
this.account = account;
}
}