博客系统后端设计(二) - 封装数据库操作

本文介绍了如何在Java中封装数据库操作,包括创建db.sql文件来定义数据库结构,封装数据库连接,创建Blog和User实体类,以及在BlogDao和UserDao中实现增、删、查操作。重点讲述了add、selectById、selectAll和delete方法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


博客系统后端的其他设计:

1.准备工作与设计数据库

2.获取博客列表页功能

3.获取博客详情页功能

4.登录页面功能

5.登录页面的强制要求登录功能

6.显示用户信息与注销功能

7.发布功能

封装数据库操作


这个步骤主要是把一些基本的数据库操作封装好,以后备用。

1. 创建一个 db.sql 文件




src 目录下创建一个 db.sql 文件,在这个文件里实现 建库建表 的语句。

-- 这个文件是用来写建库建表的语句的
-- if not exists 是判断当前要创建的数据是否存在
create database if not exists blog_system;

use blog_system;

-- 删除旧表,重新创建新表,删除是为了残留的数据对后续的程序有负面影响
-- if not exists 是为了判断当前的表是否存在
drop table if not exists user;
drop table if not exists blog;

-- 创建博客表
create table blog (
    blogId int primary key auto_increment,
    title varchar(128),
    content varchar(4096),
    postTime dateTime,
    userId int
);

-- 创建用户表
create table user (
    userId int primary key auto_increment,
    username varchar(20) unique, -- 要求用户名要和别人不重复
    password varchar(20)
);

2. 封装数据库的连接操作


要新建一个 DBUtil 类,在这个类当中实现以下代码。

public class DBUtil {
   
    private static DataSource dataSource = new MysqlDataSource();

    static {
   
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        // 你的数据库密码是什么就写什么,没有就不写
        ((MysqlDataSource) dataSource).setPassword("000000");
    }
    
    // 通过这个方法来建立连接
    public static Connection getConnection() throws SQLException {
   
        return dataSource.getConnection();
    }

    // 通过这个方法来释放资源
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
   
        if (resultSet != null) {
   
            try {
   
                resultSet.close();
            } catch (SQLException e) {
   
                e.printStackTrace();
            }
        }

        if (statement != null) {
   
            try {
   
                statement.close();
            } catch (SQLException e) {
   
                e.printStackTrace();
            }
        }

        if (connection != null) {
   
            try {
   
                connection.close();
            } catch (SQLException e) {
   
                e.printStackTrace();
            }
        }
    }
}


jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false

上述语句中的 blog_system 是你的数据库名。

3. 创建实体类


这里创建的实体类实际上就是和表中的记录对应的类。

例如:
blog 表就用 Blog 类对应,Bolg 的一个对象就对应表中的一条记录。

user 表就用 User 类对应,User 的一个对象就对应表中的一条记录。

接下来新建一个 Blog 和 User 类。


(1) 编写 Blog 类中的代码


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

与大师约会

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值