目录
4.封装数据库的增删改查操作——BlogDao类、UserDao类
准备工作
1.创建一个Maven项目
2.引入依赖
在https://mvnrepository.com/中分别搜素 mysql、servlet、jackson,引入上面三个依赖。
pom.xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyBlog</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--引入servlet依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--引入mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--引入jackson依赖-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
</dependencies>
</project>
3.创建目录结构
web.xml文件中内容
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
将写好的前端代码文件复制到webapp目录下
设计数据库
当前设计的博客系统中,主要涉及两个实体,博客和用户
一个博客只属于一个用户,一个用户可以发布多个博客
所以是一对多的情况
封装数据库
把一些基本的数据库操作封装好,方便多次使用
1.创建一个db.sql文件
在文件内实现建库键表的语句
create database if not exists java109_blog_system charset utf8;
use java109_blog_system;
drop table if exists blog;
drop table if exists user;
create table blog (
blogId int primary key auto_increment,
title varchar(1024),
content varchar(4096),
postTime datetime,
userId int
);
create table user (
userId int primary key auto_increment,
username varchar(50) unique, -- 用户名也要求是不能重复的.
password varchar(50)
);
-- 插入一些测试数据, 方便后续进行测试工作
insert into blog values (1, '这是第一篇博客', '# 从今天开始我要认真写代码', now(), 1);
insert into blog values (2, '这是第二篇博客', '# 从昨天开始我要认真写代码', now(), 1);
insert into blog values (3, '这是第三篇博客', '# 从前天开始我要认真写代码', now(), 1);
insert into user values (1, 'zhangsan', '123');
insert into user values (2, 'lisi', '123');
2.封装数据库连接操作——DBUtil类
创建DBUtil类,通过这个类,封装数据库连接操作
package model;
//import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
//通过这个类 封装数据库连接操作
//接下来有多个Servlet都需要使用数据库
public class DBUtil {
private volatile static DataSource dataSource=null;
public static DataSource getDataSource() {
if(dataSource==null){
dataSource=new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109_blog_system?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("200407");
}
return dataSource;
}
public static Connection getConnection() throws SQLException {
return (Connection) getDataSource().getConnection();
}
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
jdbc:mysql://127.0.0.1:3306/java109_blog_system?characterEncoding=utf8&useSSL=false
上述语句中的 java109_blog_system 是你的数据库名。
3.创建实体类—— Blog 类、 User 类
blog 表就用 Blog 类对应,Bolg 的一个对象就对应表中的一条记录。
user 表就用 User 类对应,User 的一个对象就对应表中的一条记录。
(1) 编写 Blog 类中的代码
package model;
import java.security.Timestamp;
import java.text.SimpleDateFormat;
//Blog对象对应到blog表中的一条记录
public class Blog {
private int blogId;
private String title;
private String content;
private java.sql.Timestamp postTime;
private int userId;
public int getUserId() {
return userId;
}
public int getBlogId() {
return blogId;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
public String getPostTime() {
// Java 标准库提供了一个 SimpleDateFormat 类, 完成时间戳到格式化时间的转换.
// 这个类的使用, 千万不要背!!! 都要去查一下!! 背大概率会背错!!!
// 把时间戳转成 格式化 时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(postTime);
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setBlogId(int blogId) {
this.blogId = blogId;
}
public void setContent(String content) {
this.content = content;
}
public void setTitle(String title) {
this.title = title;
}
public void setPostTime(java.sql.Timestamp postTime) {
this.postTime = postTime;
}
@Override
public String toString() {
return "Blog{" +
"blogId=" + blogId +
", title='" + title + '\'' +
", content='" + content + '\'' +
", postTime=" + postTime +
", userId=" + userId +
'}';
}
}
(2) 编写 User 类中的代码
package model;
public class User {
private String username;
private int userId;
private String password;
public int getUserId() {
return userId;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", userId=" + userId +
", password='" + password + '\'' +
'}';
}
}
4.封装数据库的增删改查操作——BlogDao类、UserDao类
(1)创建BlogDao类,通过这个类来完成对blog表的操作
package model;
import java.sql.Connection;
import java.lang.reflect.Parameter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//通过BlogDao来完成针对blog表的操作
public class BlogDao {
//1.新增操作(提交博客)
public void insert(Blog blog) {
Connection connection = null;
PreparedStatement statement = null;
try {
//1.建立连接
connection = DBUtil.getConnection();
//2.构造sql
String sql = "insert into blog values (null,?,?,now(),?)";//blogId是自增主键,设置为null让它自动分配就可以
// 替换操作 //“?”表示占位符
statement = connection.prepareStatement(sql);
statement.setString(1, blog.getTitle());
statement.setString(2, blog.getContent());
statement.setInt(3, blog.getUserId());
//3.执行sql
statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException();
} finally {
// 4.释放资源
DBUtil.close(connection, statement, null);
}
}
//2.查询博客列表(博客列表页)
//把数据库中的博客都拿到
public List<Blog> getBlogs() {
List<Blog> blogList=new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet=null;
try{
//1.建立连接
connection = DBUtil.getConnection();
//2.构造sql
String sql = "select * from blog order by postTime desc";//使博客列表页的博客按发布时间降序排,后发的在上面显示
statement = connection.prepareStatement(sql);
//3.执行sql
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");
// 需要注意的是在博客列表页是不需要把整个正文全部显示出来的
// 这里可以可以设置一个显示的篇幅,如100字
if(content.length()>100)
content=content.substring(0,100)+"...";
blog.setContent(content);
blog.setPostTime(resultSet.getTimestamp("postTime"));
blog.setUserId(resultSet.getInt("userId"));
// 调用 add 方法添加进去
blogList.add(blog);
}}
catch(SQLException e){
throw new RuntimeException(e);
}
finally {
// 释放资源
DBUtil.close(connection,statement,resultSet);
}
return blogList;
}
//3.根据博客id查询指定博客
public Blog getBlog(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet=null;
try{
//1.建立连接
connection = DBUtil.getConnection();
//2.构造sql
String sql = "select * from blog where blogId=?";
statement = connection.prepareStatement(sql);
statement.setInt(1,blogId);
//3.执行sql
resultSet=statement.executeQuery();
// 此时的查询结果要么是没有查到任何数据,要么只有一条记录,使用 if 判定即可
if(resultSet.next()){
Blog blog = new 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 {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
//根据id删除指定博客
public void delete(int blogId) throws SQLException {
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
statement.executeUpdate();}
catch (SQLException throwables) {
throwables.printStackTrace();
}
finally {
DBUtil.close(connection,statement,null);
}
}
}
以上方法的大致实现方式是一致的,都要 和数据库建立连接、构造 sql 语句、执行 sql 语句、还有就是最后的释放资源。
对于查询操作会有一个遍历结果集合的步骤,其余的步骤也是一致的。
在执行 sql 语句的时候,如果是 增删改 就要使用 executeUpdate,如果是 查询 操作,就要使用 executeQuery
(2)创建 UserDao类,通过这个类来完成对user表的操作
package model;
import java.lang.ref.PhantomReference;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
//根据userId查到对应的用户信息
public User getUserById(int userId) {
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
try{
connection=DBUtil.getConnection();
String sql="select * from user where userId=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,userId);
resultSet=statement.executeQuery();
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 {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
//根据username查到对应的用户信息
public User getUserByName(String username) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from user where username=?";
statement = connection.prepareStatement(sql);
statement.setString(1, username);
resultSet = statement.executeQuery();
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 {
DBUtil.close(connection, statement, resultSet);
}
System.out.println("222");
return null;
}
}