Java/JavaWeb 连接数据库完成增删改查

2年前 (2022) 程序员胖胖胖虎阿
410 0 0

Java/JavaWeb 连接数据库完成增删改查
🍖🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖
🍖🍖
🍖🍖🍖
🍖🍖🍖🍖 作者 : 不良使
🍖🍖🍖🍖🍖 潜力创作新星 华为云享专家
🍖🍖🍖🍖🍖🍖 博客记录学习的思路,项目和错误,寻找志同道合的朋友
🍖🍖🍖🍖🍖🍖🍖 如果觉得有帮助记得一键三连 ┗|`O′|┛ 嗷~~
🍖🍖🍖🍖🍖🍖🍖🍖

🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖🍖 🍖🍖🍖🍖🍖🍖🍖

连接数据库无非就是和数据库建立连接,和前面的python连接数据库差不多。


首先在连接Java数据库的时候需要数据库的jar包,这点不同于python连接数据库
mysql的jar包

下面让我们来看看数据库是如何让连接的,是如何完成数据库的一系列操作,增删改查等…


💖Java连接数据库。

🎶1、注册驱动

Class.forName("com.mysql.jdbc.Driver");

🎶2、获取连接

  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "123456");

注意:获取连接很重要,数据的一点点错误都会导致你连接不上数据库。
😃1、localhost代表本机不用变
😃2、3306是端口号,即port,一般默认都是3306。
😃3、root一般指管理员,不用变,直接用即可。
😃4、"123456"指的是密码,一般大家常用的密码就123、111111、root或者123456几种。


🎶3、获取数据库操作对象

stmt = conn.createStatement();

🎶4、//执行sql

 String sql = "select id,name,num,price from testmodel_car";
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String num = rs.getString("num");
                String price = rs.getString("price");
                System.out.println(id + "," + name + "," + num + "," + price);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

注意:
😃1、java"select id,name,num,price from testmodel_car";从表 testmodel_car中查询 id,name,num,price四列数据
😃2、rs = stmt.executeQuery(sql);获取的对象编译一下sql语句
😃3、String id = rs.getString("id");取出id那一列的值赋值给id(String id 中的id可以随便换,只要不和其他变量冲突都是可以的)


🎶5、释放资源

       if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

不释放资源也行,在上面抛出异常也可以解决


🎶6、完整代码

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test2 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "123456");
            //获取数据库操作对象
            stmt = conn.createStatement();
            //执行sql
            String sql = "select id,name,num,price from testmodel_car";
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String num = rs.getString("num");
                String price = rs.getString("price");
                System.out.println(id + "," + name + "," + num + "," + price);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


💖连接数据库------增加操作

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: 17331
  Date: 2022/3/5
  Time: 15:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="h/favicon2.ico" rel="icon" type="image/x-icon"/>
    <title>添加信息</title>
    <style>
        body {
            background-color:#FDF5E6;
        }
    </style>
    <style>
        body {
            width: 100%;
            height: 100%;
            background: url('./img/olypic.jpg');
            background-repeat: no-repeat;
            background-size: 100% 100%;
            background-attachment: fixed;
        }
    </style>
    <style>
        input{
            width: 20%;
            padding: 12px 20px;
            margin: 8px 0;
            box-sizing: border-box;
            border: 1px solid #555;
            outline: none;
        }

        input:focus {
            background-color: lightblue;
        }
    </style>
    <style>
        #boxshadow {
            position: relative;
            -moz-box-shadow: 1px 2px 4px rgba(0, 0, 0,0.5);
            -webkit-box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
            box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
            padding: 10px;
            background:#F0F8FF;
            border-radius:8px;
        }

        /* Make the image fit the box */
        #boxshadow img {
            width: 50%;
            border: 0px solid #8a4419;
            border-style: inset;
        }

        #boxshadow::after {
            content: '';
            position: absolute;
            z-index: -1; /* hide shadow behind image */
            -webkit-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
            -moz-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
            box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);
            width: 70%;
            left: 15%; /* one half of the remaining 30% */
            height: 100px;
            bottom: 0;
        }
    </style>
    <style>
        .button {
            background-color:#337AB7; /* Green */
            border: none;
            color: white;
            padding: 16px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            -webkit-transition-duration: 0.4s; /* Safari */
            transition-duration: 0.4s;
            cursor: pointer;
        }

        .button1 {
            background-color: white;
            color: black;
            border: 2px solid #337AB7;
        }
        .button1:hover {
            background-color: #337AB7;
            color: white;
            box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
        }
    </style>

</head>
<body>

<div style="padding:2px;width:1080px;height:470px;margin-top:10%;margin-left:20%;opacity: 0.8" id="boxshadow">
    <div>
        <img src="img/olypic.jpg"   style="float:left;margin-top:5%;">
    </div>
    <div style="float:right;">
        <form action="add" method="post">
            <p style="margin-right:200px;">
                国家名称&nbsp&nbsp&nbsp<input type="text"  name="Country"  style="border-radius:8px;width:150px;height:30px;">
            </p>
            <p>
                &nbsp&nbsp金牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="Glod_num" style="border-radius:8px;width:150px;height:30px;margin-top:1%">
            </p>

            <p>
                &nbsp&nbsp银牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="Silver_num" style="border-radius:8px;width:150px;height:30px;margin-top:1%">
            </p>
            <p>
                &nbsp&nbsp铜牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="Copper_num" style="border-radius:8px;width:150px;height:30px;margin-top:1%">
            </p>
            <p>
                &nbsp&nbsp&nbsp&nbsp&nbspid&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="id" style="border-radius:8px;width:150px;height:30px;margin-top:1%">
            </p>
            <input type="submit" value="保存"/><br/>
        </form>
        </form>
    </div>
</div>
</body>
</html>

Add.java

package com.bjpowernode.javaweb.servlet;

import com.bjpowernode.javaweb.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;


@WebServlet(name = "add", value = "/add")
public class Add extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //获取信息,前端页面注册的信息
        String country=request.getParameter("Country");
//        String logo=request.getParameter("logo");
        String Glod_num=request.getParameter("Glod_num");
        String Silver_num=request.getParameter("Silver_num");
        String Copper_num=request.getParameter("Copper_num");
        String id =request.getParameter("id");
//        String Sum=request.getParameter("Sum");
        //连接数据库,执行insert插入语句
        Connection conn = null;
        PreparedStatement ps = null;
        int count=0;
        try {
            //注册驱动
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mofa", "root", "123456");

            // TODO 2、开启事务   默认开启  我们将它关闭()自动提交机制关闭
            String sql = "insert ignore into medals_table(Country,Glod_num,Silver_num,Copper_num,id) values (?,?,?,?,?);";
            ps = conn.prepareStatement(sql);
            ps.setString(1, country);
//            ps.setString(2, logo);
            ps.setString(2, Glod_num);
            ps.setString(3, Silver_num);
            ps.setString(4, Copper_num);
            ps.setString(5, id);
//            ps.setString(7, Sum);
            //返回一个值,指的是  影响了数据库中多少条记录  主要是判断是否大于0  就是是否印象数据库
            count = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DButil.close(conn,ps,null);
        }
        if(count==1){
            //增加成功   任然跳到列表页面
            request.getRequestDispatcher("Take_01").forward(request,response);
        }
        else{
            //删除失败
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

Java/JavaWeb 连接数据库完成增删改查
增加功能就是通过前端jsp文件text填写数据,然后通过submit提交数据,传递给后端servlet,也就是上面的Add,注意Java文件不要小写,我就没少挨骂

步骤:
😘1前端jsp文件text写入通过submit提交
😘2<form action="add" method="post">通过form表单提交给后端的servel(Add)
😘3String country=request.getParameter("Country");通过getParameter取到前端的值然后赋值给country,为后面刷数据做准备
😘
4
后端servlet访问数据库,步骤访问上面第一个标题《Java连接数据库》
😘5成功将前端传来的数据刷如数据库



💖连接数据库------删除操作

package com.bjpowernode.javaweb.servlet;

import com.bjpowernode.javaweb.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "delete", value = "/delete")
public class Delete extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //根据部门编号删除部门
        //获取部门编号
        String country = request.getParameter("name");
        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count=0;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mofa", "root", "123456");
            // TODO 2、开启事务   默认开启  我们将它关闭()自动提交机制关闭
            conn.setAutoCommit(false);
            String sql = "delete from medals_table where Country=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,country);
            //返回一个值,指的是  影响了数据库中多少条记录  主要是判断是否大于0  就是是否印象数据库
            count= ps.executeUpdate();
            //事务提交
            conn.commit();

        } catch (SQLException e) {
            if(conn!=null){
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            DButil.close(conn,ps,null);
        }
        if(count==1){
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('Dear, the deletion is unrecoverable. Are you sure you deleted it?');");
            out.println("location.href='Take_01'");//跳转到用户列表页面
            out.println("</script>");
//            //删除成功   任然跳到列表页面
//            request.getRequestDispatcher("Take_01").forward(request,response);

        }
        else{
            //删除失败
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

String country = request.getParameter("name");老规矩,前端取值进行操作


💖连接数据库------修改操作

edit.jsp

<%--
  Created by IntelliJ IDEA.
  User: 17331
  Date: 2022/3/6
  Time: 17:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title><%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <html>
        <head>
        <title>新增</title>
</head>
<body>
<h1>新增国家奖牌信息</h1>
<hr color="red" width="100%">
<form action="edit" method="post">
    国家名称 :<input type='text' name='Country' value='"+country+"'/><br/>
<%--    logo :<input type='text' name='logo' value='"+logo+"'/><br/>--%>
    金牌数 :<input type='text' name='Glod_num' value='"+Glod+"'/><br/>
    银牌数 :<input type='text' name='Silver_num' value='"+Silver+"'/><br/>
    铜牌数 :<input type='text' name='Copper_num' value='"+Copper+"'/><br/>
    id  : <input type='text' name='Sum' value='"+sum+"'/><br/>
    总数 : <input type='text' name='id' value='"+id+"'/><br/>
    <input type="submit" value="保存"/><br/>
</form>
</body>
</html>

Edit.java

package com.bjpowernode.javaweb.servlet;

import com.bjpowernode.javaweb.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "edit",value = "/edit")
public class Edit extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out =response.getWriter();
        //jsp文档
        out.println("<html lang='en'>");
        out.println("<head>");
        out.println("    <meta charset='UTF-8'>");
        out.println("    <link href='h/favicon2.ico' rel='icon' type='image/x-icon'/>");
        out.println("    <title>添加信息</title>");
        out.println("    <style>");
        out.println("                body {");
        out.println("            background-color:#FDF5E6;");
        out.println("        }");
        out.println("    </style>");
        out.println("    <style>");
        out.println("                body {");
        out.println("            width: 100%;");
        out.println("            height: 100%;");
        out.println("            background: url('./img/olypic.jpg');");
        out.println("            background-repeat: no-repeat;");
        out.println("            background-size: 100% 100%;");
        out.println("            background-attachment: fixed;");
        out.println("        }");
        out.println("    </style>");
        out.println("    <style>");
        out.println("                input{");
        out.println("            width: 20%;");
        out.println("            padding: 12px 20px;");
        out.println("            margin: 8px 0;");
        out.println("            box-sizing: border-box;");
        out.println("            border: 1px solid #555;");
        out.println("            outline: none;");
        out.println("        }");
        out.println("");
        out.println("        input:focus {");
        out.println("            background-color: lightblue;");
        out.println("        }");
        out.println("    </style>");
        out.println("    <style>");
        out.println("        #boxshadow {");
        out.println("            position: relative;");
        out.println("            -moz-box-shadow: 1px 2px 4px rgba(0, 0, 0,0.5);");
        out.println("            -webkit-box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);");
        out.println("            box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);");
        out.println("            padding: 10px;");
        out.println("            background:#F0F8FF;");
        out.println("            border-radius:8px;");
        out.println("        }");
        out.println("");
        out.println("        /* Make the image fit the box */");
        out.println("        #boxshadow img {");
        out.println("            width: 50%;");
        out.println("            border: 0px solid #8a4419;");
        out.println("            border-style: inset;");
        out.println("        }");
        out.println("");
        out.println("        #boxshadow::after {");
        out.println("            content: '';");
        out.println("            position: absolute;");
        out.println("            z-index: -1; /* hide shadow behind image */");
        out.println("            -webkit-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);");
        out.println("            -moz-box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);");
        out.println("            box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3);");
        out.println("            width: 70%;");
        out.println("            left: 15%; /* one half of the remaining 30% */");
        out.println("            height: 100px;");
        out.println("            bottom: 0;");
        out.println("        }");
        out.println("    </style>");
        out.println("    <style>");
        out.println("       .button {");
        out.println("            background-color:#337AB7; /* Green */");
        out.println("            border: none;");
        out.println("            color: white;");
        out.println("            padding: 16px 32px;");
        out.println("            text-align: center;");
        out.println("            text-decoration: none;");
        out.println("            display: inline-block;");
        out.println("            font-size: 16px;");
        out.println("            margin: 4px 2px;");
        out.println("            -webkit-transition-duration: 0.4s; /* Safari */");
        out.println("            transition-duration: 0.4s;");
        out.println("            cursor: pointer;");
        out.println("        }");
        out.println("");
        out.println("       .button1 {");
        out.println("            background-color: white;");
        out.println("            color: black;");
        out.println("            border: 2px solid #337AB7;");
        out.println("        }");
        out.println("       .button1:hover {");
        out.println("            background-color: #337AB7;");
        out.println("            color: white;");
        out.println("            box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);");
        out.println("        }");
        out.println("    </style>");
        out.println("");
        out.println("</head>");
        out.println("<body>");
        out.println("");
        out.println("<div style='padding:2px;width:1080px;height:470px;margin-top:10%;margin-left:20%;opacity: 0.8' id='boxshadow'>");
        out.println("    <div>");
        out.println("        <img src='img/olypic.jpg'   style='float:left;margin-top:5%;'>");
        out.println("    </div>");
        out.println("    <div style='float:right;'>");
        out.println("		<form action='"+contextPath+"/update' method='post'>");




        //获取国家名称
        String country=request.getParameter("name");
        //连接数据库
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mofa", "root", "123456");
            String sql = "select * from medals_table where Country=?";
            //编译sql语句
            ps = conn.prepareStatement(sql);
            //赋值    第一个问好赋值 country   国家名称
            ps.setString(1, country);
            //查询返回结果集    这个结果集只有一条记录  ,国家名称是主键  ,  故只有一条数据
            rs = ps.executeQuery();
            if(rs.next()){
                String logo=rs.getString("logo");
                String Glod = rs.getString("Glod_num");
                String Silver = rs.getString("Silver_num");
                String Copper = rs.getString("Copper_num");
                String sum=rs.getString("Sum");
                String id=rs.getString("id");
                System.out.println("你好,你好,你好,齐天大圣!!!");
                //输出动态网页
                out.println("<p style='margin-right:200px;'>");
                out.println("                        国家名称&nbsp&nbsp&nbsp<input type='text'  name='Country'  value='"+country+"' style='border-radius:8px;width:150px;height:30px;'>");
                out.println("            </p>");
//                out.println("            <p>");
//                out.println("                        &nbsp&nbsp&nbsplogo&nbsp&nbsp&nbsp&nbsp&nbsp <input type='text' name='logo' value='"+logo+"' style='border-radius:8px;width:150px;height:30px;margin-top:1%'>");
//                out.println("            </p>");
                out.println("            <p>");
                out.println("                        &nbsp&nbsp金牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type='text' name='Glod_num' value='"+Glod+"' style='border-radius:8px;width:150px;height:30px;margin-top:1%'>");
                out.println("            </p>");
                out.println("");
                out.println("            <p>");
                out.println("                        &nbsp&nbsp银牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type='text' name='Silver_num' value='"+Silver+"' style='border-radius:8px;width:150px;height:30px;margin-top:1%'>");
                out.println("            </p>");
                out.println("            <p>");
                out.println("                        &nbsp&nbsp铜牌数&nbsp&nbsp&nbsp&nbsp&nbsp<input type='text' name='Copper_num' value='"+Copper+"' style='border-radius:8px;width:150px;height:30px;margin-top:1%'>");
                out.println("            </p>");
                out.println("            <p>");
                out.println("                        &nbsp&nbsp&nbsp&nbsp&nbspid&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type='text' name='id' value='"+id+"' style='border-radius:8px;width:150px;height:30px;margin-top:1%'>");
                out.println("            </p>");

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(conn,ps,rs);
        }
        out.println("            <input type='submit' value='保存'/><br/>");
out.println("      </form>");
out.println("     </form>");
out.println("  </div>");
out.println("</div>");
out.println("</body>");
out.println("</html>");

    }
}

Update.java

package com.bjpowernode.javaweb.servlet;

import com.bjpowernode.javaweb.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "update",value = "/update")
public class Update extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //解决中文乱码问题
        String country=request.getParameter("Country");
        String logo=request.getParameter("logo");
        String Glod_num=request.getParameter("Glod_num");
        String Silver_num=request.getParameter("Silver_num");
        String Copper_num=request.getParameter("Copper_num");
        String id=request.getParameter("id");
        //连接数据库执行更新操作
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count=0;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mofa", "root", "123456");
            String sql = "update medals_table set Glod_num=?,Silver_num=?,Copper_num=?,id=? where Country=?";
            //编译sql语句
            ps = conn.prepareStatement(sql);
//            ps.setString(1, logo);
            ps.setString(1, Glod_num);
            ps.setString(2, Silver_num);
            ps.setString(3, Copper_num);
            ps.setString(4, id);
            ps.setString(5, country);
//            System.out.println(logo);
            count=ps.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DButil.close(conn, ps, rs);
        }
        if(count==1){
            //更新成功
            request.getRequestDispatcher("Take_01").forward(request,response);
        }else{
            //更新失败
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}

💋1、前端传输数据给后端edit,edit通过getParameter取到前端值完成后面的操作。
💋2、为了让修改的时候可以显示修改前的值,我们在Edit.java中写入前端代码。
💋3、Edit.jav中代码通过form表单把数据传输给Update.java。
💋4、Update.java通过getParameter取到由Edit.java中传来的值。
💋5、把取到的值存进数据库,完成刷入操作。

注意:我这里有个bug,就是不能修改国家名称,因为手贱的我为了让数据库看着好看就把国家名设置为主键了,,,,,,,



💖连接数据库------查询操作

Select.java

package com.bjpowernode.javaweb.servlet;

import com.bipowernode.pojo.Olypic;
import com.bjpowernode.javaweb.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "select",value = "/select")
public class Select extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("select_name");
        System.out.println(name);
        //连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Olypic> olypicList=new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mofa", "root", "123456");
            String sql = "select * from medals_table where Country=?";
            //编译sql语句
            ps = conn.prepareStatement(sql);
            //赋值    第一个问好赋值 country   国家名称
            ps.setString(1, name);
            //查询返回结果集    这个结果集只有一条记录  ,国家名称是主键  ,  故只有一条数据
            rs = ps.executeQuery();
            if (rs.next()) {
                String country = rs.getString("Country");
                String Glod = rs.getString("Glod_num");
                String Silver = rs.getString("Silver_num");
                String Copper = rs.getString("Copper_num");
                String id=rs.getString("id");
                String logo=rs.getString("logo");
                System.out.println("这是数据");
                System.out.println(country);
                System.out.println("Glod");
//                   String Sum=rs.getString("Sum");
                int G = Integer.valueOf(Glod).intValue();
                int S = Integer.valueOf(Silver).intValue();
                int C = Integer.valueOf(Copper).intValue();
                int A=G+S+C;
                String Sum=String.valueOf(A);

                //将数据封装程Java对象
                Olypic olpic=new Olypic();
                olpic.setCountry(country);
                olpic.setGlod_num(Glod);
                olpic.setSilver_num(Silver);
                olpic.setCopper_num(Copper);
                olpic.setId(id);
                olpic.setSum(Sum);
                olpic.setLogo(logo);
                // TODO 将数据放入上面定义好的容器
                olypicList.add(olpic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            DButil.close(conn, ps, rs);
        }
        request.setAttribute("olypicList",olypicList);
        request.getRequestDispatcher("./take_03.jsp").forward(request,response);
    }
}

可以从前端或者后端传值,完成搜索操作。但是一般是要通过前端搜索框输入值,通过form表单传走,后端通过getParameter取值完成一些列操作。


现在的项目都是通过框架,但是 了解传输和运行机制还是十分重要的。

完整的JavaWeb项目







觉得有用的可以给个三连,关注一波!!!带你了解更多的Java小知识

版权声明:程序员胖胖胖虎阿 发表于 2022年10月20日 下午5:48。
转载请注明:Java/JavaWeb 连接数据库完成增删改查 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...