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


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

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 类中的代码

public class Blog {
    
    
    private int blogId;
    private String title;
    private String content;
    private Timestamp postTime;
    private int userId;
}




上面代码中的成员要和 blog 表中的属性一样。

在上述代码的基础上还要生成 Getter 和 Setter 方法。

右击之后,点击圈出的位置



之后再出现的界面中点击 Getter and Setter



把界面中出现的成员全选,点击 ok 即可。



完整的代码

import java.sql.Timestamp;

public class Blog {
    
    
    private int blogId;
    private String title;
    private String content;
    private Timestamp postTime;
    private int userId;

    public int getBlogId() {
    
    
        return blogId;
    }

    public void setBlogId(int blogId) {
    
    
        this.blogId = blogId;
    }

    public String getTitle() {
    
    
        return title;
    }

    public void setTitle(String title) {
    
    
        this.title = title;
    }

    public String getContent() {
    
    
        return content;
    }

    public void setContent(String content) {
    
    
        this.content = content;
    }

    public Timestamp getPostTime() {
    
    
        return postTime;
    }

    public void setPostTime(Timestamp postTime) {
    
    
        this.postTime = postTime;
    }

    public int getUserId() {
    
    
        return userId;
    }

    public void setUserId(int userId) {
    
    
        this.userId = userId;
    }
}



(2) 编写 User 类中的代码

User 也要注意这些成员要和 user 表中的属性一致。



其余的步骤可 (1) 一致,以下是完整的代码。

public class User {
    
    
    private int userId;
    private String username;
    private String password;

    public int getUserId() {
    
    
        return userId;
    }

    public void setUserId(int userId) {
    
    
        this.userId = userId;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

4. 封装数据库的增删改查操作


创建一个 BlogDao 和 UserDao 类,在这个类中实现一些方法来进行增删改查操作。

4.1 创建 BlogDao 类中的方法


通过这个类,封装针对 博客表 的基本操作,
此处暂时不涉及到修改操作,修改操作也可以通过删除和新增来实现。

public class BlogDao {
    
    
    // 1.新增一个博客
    public void add(Blog blog) {
    
    

    }

    // 2.根据博客 id 来查询指定博客(博客详情页)
    public Blog selectById(int blogId) {
    
    
        return null;
    }

    // 3.直接查询出数据库中所有的博客列表(博客列表页)
    public List<Blog> selectAll() {
    
    
        return null;
    }
    
    // 4.删除指定博客
    public void delete(int blogId) {
    
    
        
    }
}



点击 发布文章 的时候就会触发 add 方法新增一个博客。
博客列表页 点击 查看全文的时候就会触发 selectById 来跳转到 博客详情页
selectAll 方法可以查询出所有的博客列表,delete 方法对应的删除按钮后续在实现。


① 实现 add 方法,实现新增操作。

// 1.新增一个博客
public void add(Blog blog) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造 sql
        String sql = "insert into blog values(null, ?, ?, ?, ?)";
        statement = connection.prepareStatement(sql);
        // 替换操作
        statement.setString(1, blog.getTitle());
        statement.setString(2, blog.getContent());
        statement.setTimestamp(3, blog.getPostTime());
        statement.setInt(4, blog.getUserId());
        // 3.执行 sql
        statement.executeUpdate();
    } catch (SQLException e) {
    
    
        e.printStackTrace();
    }finally {
    
    
        // 4.释放资源
        DBUtil.close(connection, statement, null);
    }
}


因为是一个新增操作,因此这里涉及的 sql 语句是 insert into blog values()

values 里的参数是要和之前建好的 blog 表是一致的。



因为自增主键不需要手动设置,设置为 null 让它自动分配即可,因此 第一个参数是 null。
以后的几个参数都使用 ? 这个占位符 来代替,在之后的操作中再将它替换为 blog 表中对应的属性。
因此后面几个参数都是 ?。因此构造的 sql 语句就是:insert into blog values(null, ?, ?, ?, ?)


② 实现 selectById 方法来查询指定博客

// 2.根据博客 id 来查询指定博客(博客详情页)
public Blog selectById(int blogId) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造查询 sql
        String sql = "select * from blog where biogId = ?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, blogId);
        // 3.执行 sql
        resultSet = statement.executeQuery();
        // 4.遍历结果集和 由于 blogId 在 bolg 表中是唯一的(主键)
        // 此时的查询结果要么是没有查到任何数据,要么只有一条记录
        // 此处可以不使用 while,使用 if 判定即可
        if (resultSet.next()) {
    
    
            Blog blog = new Blog();
            // 把从数据库中读到信息设置到 blog 对象中
            blog.setBlogId(resultSet.getInt("blogId"));
            blog.setTitle(resultSet.getString("title"));
            blog.setContent(resultSet.getString("content"));
            blog.setPostTime(resultSet.getTimestamp("postTime"));
            blog.setUserId(resultSet.getInt("userId"));
            return blog;
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    }finally {
    
    
        // 4.释放资源
        DBUtil.close(connection, statement, resultSet);
    }
    return null;
}


因为是要完成指定查询,因此它的 sql 语句是 select * from blog where biogId = ?
将方法中的参数 blogId 替换到 占位符中以完成指定条件的查询。

在遍历结果集合的时候,由于 blogId 在 bolg 表中是唯一的(主键),因此查询的结果要么是没有查到任何数据,要么只有一条记录。

因此在此处可以不使用 while,使用 if 判定一次即可。


③ 实现 selectAll 方法 查询所有的博客列表

// 3.直接查询出数据库中所有的博客列表(博客列表页)
public List<Blog> selectAll() {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List<Blog> blogs = new ArrayList<>();
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造查询 sql
        String sql = "select * from blog";
        statement = connection.prepareStatement(sql);
        // 3.执行sql - 增删改 使用 executeUpdate 查使用 executeQuery
        resultSet = statement.executeQuery();
        // 4.遍历结果集合
        while (resultSet.next()) {
    
    
            Blog blog = new Blog();
            // 把从数据库中读到信息设置到 blog 对象中
            blog.setBlogId(resultSet.getInt("blogId"));
            blog.setTitle(resultSet.getString("title"));
            // 需要注意的是在博客列表页是不需要把整个正文全部显示出来的
            // 这里可以可以设置一个显示的篇幅
            String content = resultSet.getString("content");
            // 将篇幅的长度设置为 128
            if (content.length() >= 128) {
    
    
                // 如果篇幅大于 128 就提取 128 长度的篇幅
                // 这只是一个随便设置的篇幅长度
                // 如果最终显示出来效果不好看,还可以随时更改
                content = content.substring(0, 128) + "...";
            }
            blog.setContent(content);
            blog.setPostTime(resultSet.getTimestamp("postTime"));
            blog.setUserId(resultSet.getInt("userId"));
            // 调用 add 方法添加进去
            blogs.add(blog);
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    } finally {
    
    
        //  释放资源
        DBUtil.close(connection, statement, resultSet);
   }
    return blogs;
}


需要注意的是在 博客列表页 是不需要把整个正文全部显示出来的,
因此这里可以设置显示出的篇幅长度。

这里设置的为 128,这只是一个随便设置的长度,如果最终显示出来效果不好看,还可以随时更改。

这里是要将所有的博客列表查询出来,因此此处使用 while 来遍历结果集和。


④ 实现 delete 删除指定博客

 // 4.删除指定博客
 public void delete(int blogId) {
    
    
     Connection connection = null;
     PreparedStatement statement = null;
     try {
    
    
         // 1.和数据库建立连接
         connection = DBUtil.getConnection();
         // 2.构造查询 sql
         String sql = "delete * from blog where blogId = ?";
         statement = connection.prepareStatement(sql);
         statement.setInt(1, blogId);
         // 3.执行sql - 增删改 使用 executeUpdate 查使用 executeQuery
         statement.executeUpdate();
     } catch (SQLException throwables) {
    
    
         throwables.printStackTrace();
     } finally {
    
    
         DBUtil.close(connection, statement, null);
     }
 }


删除操作就是会通过方法里的参数 blogId 来找到要删除的博客,然后删除。
以上四个方法的大致实现方式是一致的,只是有个别的操作不同。

都要 和数据库建立连接、构造 sql 语句、执行 sql 语句、还有就是最后的释放资源
对于查询操作会有一个遍历结果集合的步骤,其余的步骤也是一致的。

以及就是在执行 sql 语句的时候,如果是 增删改 就要使用 executeUpdate
如果是 查询 操作,就要使用 executeQuery

4.2 创建 UserDao 类中的方法


通过这个类,封装针对 博客表 的基本操作。

// 1.根据 userId 来查用户信息
public User selectById(int userId) {
    
    

}

// 2.根据 username 来查用户信息
public User selectByUsername(String username) {
    
    
    
}



① 实现 selectById 方法,根据 userId 查询用户信息。

// 1.根据 userId 来查用户信息
public User selectById(int userId) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造 sql 语句
        String sql = "select * from user where userId = ?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        // 3.执行 sql
        resultSet = statement.executeQuery();
        // 4.遍历结果集合
        if (resultSet.next()) {
    
    
            User user = new User();
            user.setUserId(resultSet.getInt("userId"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    } finally {
    
    
        // 5.释放资源
        DBUtil.close(connection, statement, resultSet);
    }
    return null;
}



② 实现 selectByUsername 方法,根据 username 查询用户信息。

这个方法与上面的方法类似,只是有两个步骤是不同的。

第一个步骤:

将上面方法构造出的 sql 语句: select * from user where userId = ?
改为了下面的 sql 语句。

// 2.构造 sql 语句
String sql = "select * from user where username = ?";


第二个步骤:

将上面方法中的 **statement.setInt(1, userId);**这条语句改为以下的这条语句。

statement.setString(1, username);


主要是将 int 类型 改为了 String 类型,以及 userId 改为了 username。

猜你喜欢

转载自blog.csdn.net/m0_63033419/article/details/130472825
今日推荐