当前位置:网站首页>数据库JDBC DAO层方法
数据库JDBC DAO层方法
2022-08-04 05:33:00 【Jorge666】
public class BaseDao {
public static final String URL = "jdbc:mysql://localhost:3306/school?useunicode=true&characterEncoding=utf-8";
public static final String USER = "root";
public static final String PASSWORD = "1234";
public static final String Driver = "com.mysql.jdbc.Driver";
public static Connection getConnection() {
Connection connection = null;
try {
// 1.加载驱动
Class.forName(Driver);
// 2建立连接
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static int commonExecuteUpdate(String sql, Object[] params) {
int row = 0;
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setString(i + 1, params[i].toString());
}
row = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResources(preparedStatement, connection, null);
}
return row;
}
public static ResultSet commonExecuteQuery(String sql, Object[] params) {
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setString(i + 1, params[i].toString());
}
resultSet = preparedStatement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void closeResources(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}以连接到本地school数据库为例
边栏推荐
猜你喜欢

关于网络安全行业你知道多少?

Completely remove MySQL tutorial

Question 1000: Input two integers a and b, calculate the sum of a+b, this question is multiple sets of test data

通用解决端口占用问题

并发概念基础:并发、同步、阻塞

安装Apache服务时出现的几个问题, AH00369,AH00526,AH00072....

C语言对文件的操作(完整版)

IDEA创建Servlet步骤

Fabric v1.1 environment construction

IDEA中创建web项目实现步骤
随机推荐
基于Webrtc和Janus的多人视频会议系统开发6 - 从Janus服务器订阅媒体流
C语言数组的深度分析
IDEA创建Servlet步骤
线性表之动态数组(ArrayList)的自实现
新冠病毒和网络安全的异同及思考
MVC自定义配置
const int * a 与 int * const a 的定义与区别
基于语音识别的QT设计的csgo互动类视频游戏
更改软件的默认安装位置
Pipe redirection
Unity Day03
使用cef离屏渲染技术实现在线教育课件和webrtc视频回放融合录制
C语言无符号整型运算
分布式cache项目
[Development Miscellaneous][Editor][Code Reading]ctags & vim
LeetCode_Nov_5th_Week
MVC custom configuration
指针运算相关面试题详解【C语言】
动态内存管理-C语言
(位操作符)按位与、按位或、按位异或