当前位置:网站首页>数据库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数据库为例
边栏推荐
猜你喜欢

target has libraries with conflicting names: libcrypto.a and libssl.a.

Design and implementation of legal aid platform based on asp.net (with project link)

LeetCode_Dec_2nd_Week

JVM三大常量池与方法区

【HIT-SC-MEMO6】哈工大2022软件构造 复习笔记6

2020-03-27

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

动态内存管理-C语言

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

Fabric v1.1 environment construction
随机推荐
冰歇webshell初探
网络通信与Socket编程概述
Fabric v1.1 环境搭建
ideal life
Multi-threaded sequential output
更改软件的默认安装位置
益智小游戏- 算算总共多少正方形
EL expression
[English learning][sentence] good sentence
[Development Miscellaneous][Editor][Code Reading]ctags & vim
使用cef离屏渲染技术实现在线教育课件和webrtc视频回放融合录制
gRPC intro 1:RPC
淘宝分布式文件系统存储引擎(一)
你要悄悄学网络安全,然后惊艳所有人
管道重定向
基于Webrtc和Janus的多人视频会议系统开发7 - publish和subscribe声音设备冲突导致对方听不到声音
MySQL索引
给想要转行渗透测试人的忠告
Chapter One Introduction
关于网络安全行业你知道多少?