封装简单MyDatabase类
/**
* 测试类
*/
public class Demo {
public static void main(String[] args) throws Exception {
Connection conn = MyDatabase.getConn();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
List<User> list = new ArrayList<>();
while (rs.next()) {
User u = new User();
u.setId(rs.getInt("id"));
u.setSigninName(rs.getString("signin_name"));
u.setPwd(rs.getString("pwd"));
list.add(u);
}
for (User user :
list) {
System.out.println(user);
}
}
}
/**
* User表实体类
*/
class User {
private int id;
private String signinName;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSigninName() {
return signinName;
}
public void setSigninName(String signinName) {
this.signinName = signinName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", signinName='" + signinName + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
/**
* 数据库工具类
*/
public class MyDatabase {
private static String driverName = null;
private static String sqlUrl = null;
private static String uid = null;
private static String pwd = null;
static {
// 读取数据库配置文件
ResourceBundle rb = ResourceBundle.getBundle("db");
driverName = rb.getString("driverName");
sqlUrl = rb.getString("sqlUrl");
uid = rb.getString("uid");
pwd = rb.getString("pwd");
// 获取数据库驱动
try {
Class.forName(driverName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建连接
*
* @return Connection 连接对象
*/
public static Connection getConn() throws Exception {
return DriverManager.getConnection(sqlUrl, uid, pwd);
}
/**
* 关闭连接 释放资源
*
* @param conn 关闭数据库链接
* @param stmt 关闭操作对象
* @param rs 释放结果集
*/
public static void kill(Connection conn, Statement stmt, ResultSet rs) throws Exception {
if (conn != null) {
conn.close();
}
if (stmt != null) {
stmt.close();
}
if (stmt != null) {
rs.close();
}
}
}