本文主要讲述了用代码对数据库的操作,maven项目创建后进行如下操作:
maven项目创建可以看这里:Servlet-day01 这里面有详细介绍
pom.xml中放置了许多外部包
<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.0modelVersion>
<groupId>com.bitgroupId>
<artifactId>java_image_servletartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>untitled15 Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.google.code.gsongroupId>
<artifactId>gsonartifactId>
<version>2.10.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.13version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>java_image_servletfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
这些包中的具体内容以及如何加入的后续都会一一解释,首先我们这里解释一下这几个
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
用于在Java项目中添加JUnit测试框架。JUnit是一个用于编写和运行单元测试的框架,可以帮助开发者确保他们的代码能够按照预期工作。
<dependency>
<groupId>com.google.code.gsongroupId>
<artifactId>gsonartifactId>
<version>2.10.1version>
dependency>
用于在Java项目中添加Google的Gson库。Gson是一个用于处理JSON数据的Java库,可以将Java对象转换为JSON字符串,也可以将JSON字符串转换为Java对象
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.13version>
dependency>
用于在Java项目中添加MySQL的JDBC驱动。这个驱动允许Java程序与MySQL数据库进行交互。
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
用于在Java Web应用程序中添加Servlet API。Servlet API提供了一组接口和类,用于开发基于Java的Web应用程序。
在Java目录下创建dao包(数据访问层,蔚然数据库展开操作),在dao包中创建DBUtil类
JDBC相关操作不清楚可以看这篇文章:0基础速成Java环境下JDBC编程(细节超全,保姆级教程)
package dao;
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.SynchronousQueue;
public class DBUtil {
//获取数据库连接
private static final String URL = "jdbc:mysql://127.0.0.1:3306/image_table?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
private static volatile DataSource dataSource = null;
public static DataSource getDataSource(){
if(dataSource == null){
Synchronized(DBUtil.class);{
if(dataSource == null){
dataSource = new MysqlDataSource();
// MysqlDataSource 对象强制转换为 MysqlDataSource 类型,
// 并使用 setURL()、setUser() 和 setPassword() 方法设置数据库连接的相关信息,包括 URL、用户名和密码。
MysqlDataSource tmpDataSour = (MysqlDataSource) dataSource;
tmpDataSour.setURL(URL);
tmpDataSour.setUser(USERNAME);
tmpDataSour.setPassword(PASSWORD);
}
}
}
return dataSource;
}
//建立连接
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
//关闭连接
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) throws RuntimeException {
if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
private static void Synchronized(Class<DBUtil> dbUtilClass) {
}
}
在java目录下的dao包中创建Image类
package dao;
public class Image {
private int imageId;//图片ID
private String imageName;//图片名字
private int size;//图片大小
private String uploadTime;//图片上传时间
private String contentType;//图片类型
private String path;//图片存储路径
private String md5;//图片md5校验和
}
自动生成get和set方法:alt+ins 选择Getter and Setter 全选,按下OK
自动生成toString方法:alt+ins 选择toString… 全选,按下OK
最后结果:
package dao;
public class Image {
private int imageId;//图片ID
private String imageName;//图片名字
private int size;//图片大小
private String uploadTime;//图片上传时间
private String contentType;//图片类型
private String path;//图片存储路径
private String md5;//图片md5校验和
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getUploadTime() {
return uploadTime;
}
public void setUploadTime(String uploadTime) {
this.uploadTime = uploadTime;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
@Override
public String toString() {
return "Image{" +
"imageId=" + imageId +
", imageName='" + imageName + '\'' +
", size=" + size +
", uploadTime='" + uploadTime + '\'' +
", contentType='" + contentType + '\'' +
", path='" + path + '\'' +
", md5='" + md5 + '\'' +
'}';
}
}
在java目录下的dao包中创建ImageDao类,借助此类完成对数据库的增删改查
package dao;
import common.JavaImageServerException;
import sun.awt.image.ImageDecoder;
import javax.imageio.IIOImage;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
//对数据库中的对象进行操作,增删改查操作
public class ImageDao {
//新增数据/插入数据(把image对象插入数据库中)
public void insert(Image image) throws SQLException {
/*
1.与数据库建立链接 Connection connection = DBUtil.getConnection();
2.创建并拼接SQL语句 String SQL= " "; PreparedStatement statement = connection.prepareStatement(SQL);注意处理异常try/catch
3.执行SQL语句 statement.setString(1,image.getImageName());
4.关闭数据库连接 DBUtil.close(connection,statement,null); 注意是否一定会执行此语句
*/
//获取数据库连接:
Connection connection = DBUtil.getConnection();
//构造并拼接SQL语句
String SQL = "INSERT INTO image VALUES(null,?,?,?,?,?,?)";
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(SQL);
//这行代码是用于创建一个 PreparedStatement 对象,该对象使用连接对象和要执行的 SQL 语句进行初始化。
//PreparedStatement 对象允许您向数据库发送 SQL 查询,从而有助于防止 SQL 注入攻击。它还允许您多次使用相同的 SQL 语句和不同的参数。
//在这个例子中,SQL 语句存储在变量 SQL 中,连接对象存储在变量 connection 中。
// 通过调用 connection 对象的 prepareStatement() 方法来创建一个新的 PreparedStatement 对象,并将其分配给变量 statement。
statement.setString(1,image.getImageName());
statement.setInt(2,image.getSize());
statement.setString(3,image.getUploadTime());
statement.setString(4,image.getContentType());
statement.setString(5,image.getPath());
statement.setString(6,image.getMd5());
int ret = statement.executeUpdate();
//这段代码是使用 JDBC API 执行 SQL 语句并返回受影响的行数。
// 其中,statement 是一个 Statement 对象,表示要执行的 SQL 语句;executeUpdate() 方法用于执行 SQL 语句,并返回受影响的行数。
// 在这个例子中,ret 变量将保存执行 SQL 语句后受影响的行数。如果执行成功,ret 的值将为正数,否则为负数。
if(ret != 1){
//ret不等于1时代表SQL语句执行失败,此时应该抛出一个异常
throw new JavaImageServerException("插入数据库出错");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (JavaImageServerException e) {
throw new RuntimeException(e);
}finally {
//关闭连接
DBUtil.close(connection,statement,null);
}
}
//查找数据库重点信息,查找全部
public List<Image> selectAll()throws SQLException {
/*
1.与数据库建立链接 Connection connection = DBUtil.getConnection();
2.创建并拼接SQL语句 String SQL= " "; PreparedStatement statement = connection.prepareStatement(SQL);
3.执行SQL语句
4.处理结果集
5.断开连接
存放结果集:
*/
List<Image> images = new ArrayList<>();//查找所有的结果返回不止一条数据,所以用列表存放结果集
Connection connection = DBUtil.getConnection();//建立数据库连接
String SQL = "select *from image;";//构造SQL语言
PreparedStatement statement = null;//statement 用于拼接SQL语言
ResultSet resultSet = null;
try{
statement = connection.prepareStatement(SQL);//拼接SQL语言
//执行SQL
resultSet = statement.executeQuery();
while (resultSet.next()){
Image image = new Image();
image.setImageId(resultSet.getInt("imageID"));
image.setImageName(resultSet.getString("imageName"));
image.setSize(resultSet.getInt("size"));
image.setUploadTime(resultSet.getString("uploadTime"));
image.setContentType(resultSet.getString("contentType"));
image.setPath(resultSet.getString("path"));
image.setMd5(resultSet.getString("Md5"));
images.add(image);
}
return images;
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(connection,statement, resultSet);
}
return null;
}
//查找数据库中的图片,按照imageID查找
public Image selectOneId(int imageId) throws SQLException{
/*
1.与数据库建立链接 Connection connection = DBUtil.getConnection();
2.创建并拼接SQL语句 String SQL= " "; PreparedStatement statement = connection.prepareStatement(SQL);
3.执行SQL语句
4.处理结果集
5.断开连接
*/
Connection connection = DBUtil.getConnection();
String SQL= "select * from image where imageId = ?";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement(SQL);
statement.setInt(1,imageId);
resultSet = statement.executeQuery();
if (resultSet.next()) {
Image image = new Image();
image.setImageId(resultSet.getInt("imageID"));
image.setImageName(resultSet.getString("imageName"));
image.setSize(resultSet.getInt("size"));
image.setUploadTime(resultSet.getString("uploadTime"));
image.setContentType(resultSet.getString("contentType"));
image.setPath(resultSet.getString("path"));
image.setMd5(resultSet.getString("Md5"));
return image;
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
//删除数据库中的图片,按照imageID删除
public void deleteOneId(int imageId) throws SQLException, JavaImageServerException {
/*
1.与数据库建立链接 Connection connection = DBUtil.getConnection();
2.创建并拼接SQL语句 String SQL= " "; PreparedStatement statement = connection.prepareStatement(SQL);
3.执行SQL语句
4.断开连接
*/
Connection connection = DBUtil.getConnection();
String SQL= "delete from image where imageId = ?";
PreparedStatement statement = null;
statement = connection.prepareStatement(SQL);
statement.setInt(1,imageId);
int ret = statement.executeUpdate();
if (ret != 1) {
//ret不等于1说明SQL没有执行,删除操作失败
throw new JavaImageServerException("删除图片信息出错");
}
DBUtil.close(connection,statement,null);
}
public static void main1(String[] args) throws SQLException {
//插入图片信息测试代码
Image image = new Image();
image.setImageName("图片4");
image.setSize(43);
image.setUploadTime("230831");
image.setContentType("图片4/png");
image.setPath("../image/图片4.png");
image.setMd5("12kwe21");
ImageDao imageDao = new ImageDao();
imageDao.insert(image);
}
public static void main(String[] args) throws SQLException {
//查找全部图片信息测试代码
ImageDao imageDao = new ImageDao();
List<Image> images = imageDao.selectAll();
System.out.println(images);
}
public static void main3(String[] args) throws SQLException {
//按照imageId查找图片信息测试代码
ImageDao imageDao = new ImageDao();
Image image = imageDao.selectOneId(2);
System.out.println(image);
}
public static void main4(String[] args) throws SQLException, JavaImageServerException {
//测试删除数据库中的图片,根据imageId
ImageDao imageDao = new ImageDao();
imageDao.deleteOneId(4);
}
}