共计 1548 个字符,预计需要花费 4 分钟才能阅读完成。
什么时候本人创立工具类
- 如果一个性能常常要用到, 咱们倡议把这个性能做成一个工具类, 能够在不同的中央重用
- 取得数据库连贯 操作, 将在当前的增删改查所有性能中都存在. 所以能够封装工具类
JDBCUtils
, 提供获取连贯对象的办法, 从而达到代码反复利用
JDBC 工具类蕴含的内容
- 自定义成员常量: 用户名 , 明码 ,URL, 驱动类
- 自定义成员办法
getConnection()
获取连贯 - 敞开所有关上的资源
JDBCUtils 示例代码
public class JDBCUtils {
private static final String DATABASE = "lianxi01";
private static final String USER = "root";
private static final String PASSWORD = "316426";
private static final String URL = "jdbc:mysql://localhost:3306/" + DATABASE + "?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
private static Connection conn = null;
private static Statement sqlExecute = null;
// a. 获取连贯
public static Connection getConnection(){
try {
// 1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 连贯数据库
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {e.printStackTrace();
} catch (SQLException throwables) {throwables.printStackTrace();
}
return conn;
}
// b. 获取语句执行平台 Statement 对象
public static Statement createStatement(Connection conn){
// 3. 获取语句执行平台
try {sqlExecute = conn.createStatement();
} catch (SQLException throwables) {throwables.printStackTrace();
}
return sqlExecute;
}
// 3. 敞开流对象 --- 未执行查问语句
public static void close(Connection conn, Statement sqlExecute){
try {if(null != sqlExecute) {sqlExecute.close();
}
if(null != conn) {conn.close();
}
} catch (SQLException throwables) {throwables.printStackTrace();
}
}
// 敞开流对象 --- 执行查问语句 办法重载
public static void close(Connection conn, Statement sqlExecute, ResultSet resultset){
try {if(null != resultset) {resultset.close();
}
if(null != sqlExecute) {sqlExecute.close();
}
if(null != conn) {conn.close();
}
} catch (SQLException throwables) {throwables.printStackTrace();
}
}
}
正文完