JDBC学习:工具集和主测试类的代码

import jdk.dynalink.beans.StaticClass;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;

public class JDBC_TEST {
private static String url;
private static String user;
private static String password;
private static String driver;

static {
Properties pro = new Properties();

ClassLoader classLoader = JDBC_TEST.class.getClassLoader();
URL res = classLoader.getResource("pro.properties");
String path = res.getPath();
//获取类加载器。类加载器调用getResource获取当前类所属的project下的src文件夹下某指定名字的文件资源(本质URL)。
// URL调用getPath获取文件绝对路径。注意绝不能有中文

try {
pro.load(new FileReader(path));
//加载配置文件,获取配置信息
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");

Class.forName(pro.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;

try {
connection = DriverManager.getConnection(url,user,password);
String sql = "select * from balance";

stmt = connection.createStatement();
rs = stmt.executeQuery(sql);

ArrayList<balance> list = new ArrayList<>();
balance b = new balance();
int a;
String name;
int balance;
while(rs.next()){
a = rs.getInt(1);
name = rs.getString("Name");
balance = rs.getInt("balance");

b.setId(a);
b.setName(name);
b.setBalance(balance);

list.add(b);
}
System.out.println(list);

} catch (Exception e) {
e.printStackTrace();
} finally {
JDBC_UTILS.close(rs,stmt,connection);
//调用工具类释放资源
}
}
}


工具类的代码:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_UTILS {

public static void close(ResultSet rs, Statement stmt, Connection con){
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

public static void close(Statement stmt, Connection con){
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}




posted @ 2021-12-26 16:45  biingpo  阅读(46)  评论(0)    收藏  举报