文章目录
博客系统后端的其他设计:
4.登录页面功能
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 类中的代码