Java-JDBC-工具类

阿࿆杰࿆ 2020-10-26 11:23:12
/*
*导入数据库需要加载的驱动包
*不是原创 根据原作者所改https://me.csdn.net/weixin_42404323?ref=miniprofile
*/
public class jdbcUtil {
/*
* 静态驱动加载 mysql驱动包
* */
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/*
* 创建连接对象
*/
public static Connection getConnection() throws SQLException {
String url="jdbc:mysql://localhost:3306/stuDB?useUnicode=true&characterEncoding=utf8";//链接地址
String user="root";//用户名
String password="123456";//密码
return DriverManager.getConnection(url, user, password);
}

/*
* 关闭增删改操作的连接对象
*/
public static void Close(Connection coon,PreparedStatement stmt) {
if (stmt!=null) {
try {
stmt.close();
coon.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 关闭读取连接对象
*/
public static void Close(Connection coon,PreparedStatement stmt,ResultSet rs) {
if (rs!=null) {
try {
rs.close();
stmt.close();
coon.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 增删改操作的方法
* String sql 执行增删改的SQL语句
* Object[] parems 操作参数
*/
public static int NonQuery(String sql,Object[] parems) {
Connection coon = null;
PreparedStatement stmt = null;
int rowCount = 0;
try {
coon = getConnection();
stmt = coon.prepareStatement(sql);
if (parems!=null&&parems.length>0) {
for (int i = 0; i < parems.length; i++) {
stmt.setObject(i+1, parems[i]);
}
}
rowCount = stmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Close(coon,stmt);
}
return rowCount;
}

/*
* 泛型查询
* String sql 执行增删改的SQL语句
* Object[] parems 操作参数
* RowsMapper<T> rm 自定义泛型类 字段读取接口 --获取实体类信息
*/
public static<T> ArrayList<T> GenericQeruy(String sql,Object[] parems,RowsMapper<T> rm){
Connection coon = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<T> list = new ArrayList<T>();
try {
coon = getConnection();
stmt = coon.prepareStatement(sql);
if (parems!=null&&parems.length>0) {
for (int i = 0; i < parems.length; i++) {
stmt.setObject(i+1, parems[i]);
}
}
rs = stmt.executeQuery();
while(rs.next()) {
T t = rm.getEntity(rs);
list.add(t);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Close(coon, stmt, rs);
}
return list;
}
}
...全文
6950 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
PinkSunspot 2020-11-26
  • 打赏
  • 举报
回复
你没有在下方创建lib文件夹,lib文件夹中方个关于连接jdbc用的jar包
幽饮烛 2020-11-09
  • 打赏
  • 举报
回复
可以考虑用代码静态检查工具扫描一遍
阿࿆杰࿆ 2020-11-09
  • 打赏
  • 举报
回复
初学者,慢慢用来的,到后面也用不到这个
KeepSayingNo 2020-10-26
  • 打赏
  • 举报
回复
代码功底深厚

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧