jdbc操作数据库 and 一个商品管理页面

news2024/11/13 15:13:30

文章目录

  • 1. 介绍
    • 1.1 应用知识介绍
    • 1.2 项目介绍
  • 2. 文件目录
    • 2.1 目录
    • 2.2 介绍以下(从上到下)
  • 3. 相关代码
    • 3.1 DBConnection.java
    • 3.2 MysqlUtil.java
    • 3.3 AddServlet.java
    • 3.4 CommodityServlet.java
    • 3.5 DelectServlet.java
    • 3.6 SelectByIdServlet.java
    • 3.7 SelectServlet.java
    • 3.8 UpdataServlet.java
    • 3.9 style.css
    • 3.10 index.js
    • 3.11 jquery-3.7.1.min.js(略)
    • 3.12 index.html
  • 4. 效果展示
  • 5. 链接
  • 6. 思考

很丑,主要学习方法

1. 介绍

1.1 应用知识介绍

基础知识:mySQL,jbdc,JQuery,ajax

mySQL中对于表的增删改查
jQuery对于前端元素的获取
ajax传递数据和获取数据

1.2 项目介绍

是一个商品管理系统,需要自己先创建好一个表如图:
表
其中类型就不多说了。
前端交互界面设计:交互
对商品数据进行增删改查

2. 文件目录

2.1 目录

目录

2.2 介绍以下(从上到下)

DBConnection.java:用于连接数据库
MysqlUtil.java:操作数据库
AddServlet.java:增加商品
CommodityServlet.java:初始化时候进行查询
DelectServlet.java:删除数据库中的相关数据
SelectByIdServlet.java:通过id获取数据
SelectServlet.java:通过名字获取数据,用于查询
UpdataServlet.java:更新数据


style.css:样式
index.js:写js
jquery-3.7.1.min.js:引入jquery
index.html:写界面

3. 相关代码

3.1 DBConnection.java

package com.qcby.db;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {

	public static void main(String[] args) {

	}

	String driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
	String user = "root";
	String password = "root";

	public Connection conn;

	public DBConnection() {

		try {
			Class.forName(driver);
			conn = (Connection) DriverManager.getConnection(url, user, password);//

			// if(!conn.isClosed())
			// System.out.println("Succeeded connecting to the Database!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			this.conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

3.2 MysqlUtil.java

package com.qcby.db;

import java.rmi.StubNotFoundException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MysqlUtil {

	public static void main(String[] args) {
		
//		String sqlcount = "select count(*) from admin";
//		String sql = "select * from admin";
//		String[] colums = {"id","account","password"};
//		String json = getJsonBySql(sqlcount, sql, colums);
//		System.out.println(json);
		
		/*String sql = "insert into t_student(name,age,sex) values(\"张三\",21,\"男\")";
        System.out.println(add(sql));*/
		
		
		/*String sqldel = "delete from gq_user where id=11";
        System.out.println(del(sqldel));*/

		/*
		 * String sqlupdate ="update user set age = 60 where name=\"you\"";
		 * System.out.println(update(sqlupdate));
		 */

		/*String sql = "select count(*) from gq_user";
		System.out.println(getCount(sql));*/
		
		/*String[] col = {"id","name","age"};
		String sql = "select * from t_student";
		String sqlCount = "select count(*) from t_student";
		String strJson = getJsonBySql(sqlCount,sql,col);
        System.out.println(strJson);*/
		
		/*String sqlcount = "select count(*) from gq_user";
		String sql="select * from gq_user";
		String[] col = {"username","age","id","sex","salary"};
		System.out.println(getJsonBySql(sqlcount, sql, col));*/

		/*
		 * String sql = "select * from user"; String[] column =
		 * {"id","name","age","entrydate"}; ArrayList<String[]> strings =
		 * MysqlUtil.showUtil(sql, column); for (String[] string : strings) {
		 * System.out.println(Arrays.toString(string)); }
		 */
	}
	/*添加*/
	public static int add(String sql) {
		// System.out.println("sql语句是:" + sql);
        int i=0;
        //数据库连接
        DBConnection db = new DBConnection();
        try {        
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            i=preStmt.executeUpdate();
            preStmt.close();
            db.close();//关闭连接 
            System.out.println("数据插入成功,sql语句是:" + sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(i);
        return i;//返回影响的行数,1为执行成功;
    }



   /*修改数据*/
    public static int update(String sql) {
        int i =0;
        DBConnection db = new DBConnection();
        try {
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            i = preStmt.executeUpdate();
            preStmt.close();
            db.close();
            System.out.println("数据更新成功,sql语句是:" + sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    

    /*删除*/
    public static int del(String delstr) {
        int i=0;
        DBConnection db = new DBConnection();
        try {    
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
            i=preStmt.executeUpdate();
            //executeUpdate()返回受影响的行数
            preStmt.close();
            db.close();
            System.out.println("数据删除成功,sql语句是:" + delstr);
        } catch (SQLException e){
            e.printStackTrace();
        }
        return i;
    }

    /*查询数量*/
    public static int getCount(String sql) {
        int sum = 0;
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while (rs.next()) {
                sum += rs.getInt(1);
            }
            rs.close();
            db.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return sum;
    }

    /**
     *功能描述 查询json数据带数据总量
     * @author 郭帅
     * @date 2021-03-22 10:30
     * @param sqlcount 查询数量的sql
     * @param sql 查询具体数据的sql
     * @param colums 查询的字段
     * @return java.lang.String
     */
    public static String getJsonBySqlDataGrid( String sqlcount,String sql,String[] colums){
        int count = getCount(sqlcount);
        System.err.println("标红信息展示sql:" + sql);
        ArrayList<String[]>  result = new ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return listToJsonDataGrid(result,colums,count);
    }
    
    /**
     *功能描述 查询json数据
     * @author 郭帅
     * @date 2021-03-22 10:30
     * @param sql 查询具体数据的sql
     * @param colums 查询的字段
     * @return java.lang.String
     */
    public static String getJsonBySql( String sql,String[] colums){
       
        System.err.println("标红信息展示sql:" + sql);
        ArrayList<String[]>  result = new ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return listToJson(result,colums);
    }

    /**
     *功能描述 查询数据
     * @author 郭帅
     * @date 2021-03-22 10:38
     * @param sql 查询具体数据的sql
     * @param colums  查询的字段
     * @return java.util.ArrayList<java.lang.String[]>
     */
    public static ArrayList<String[]> showUtil( String sql, String[] colums){

        ArrayList<String[]>  result = new  ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);

            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 转化为json数据字符串
     * @param
     * @return
     */
    public static String listToJsonDataGrid( ArrayList<String[]> list,String[] colums,int count) {

    	String jsonStr = "{\"code\":0,\"msg\":\"成功了\",\"count\":"+count+",\"data\":[";
    			for(int i = 0; i < list.size(); i++) {
    				String arr = "{";
    				for( int j = 0; j < list.get(0).length; j++) {
    					
    					if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
    						arr += "\"" + colums[j] + "\":\"\"";
    					}else {
    						arr += "\"" + colums[j] + "\""+":" ;
    						arr +=  "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
    					}
    					
    					if( j < list.get(0).length - 1 ) {
    						arr += ",";
    					}
    				}
    				arr += "}";
    				if( i < list.size() - 1 ) {
						arr += ",";
					}
    				
    				jsonStr += arr;
    			}
    			jsonStr += "]}";
    	
    	return jsonStr;
    }
    
    /**
     * 转化为json数据字符串
     * @param
     * @return
     */
    public static String listToJson( ArrayList<String[]> list,String[] colums) {

    	String jsonStr = "{\"code\":0,\"msg\":\"成功了\",\"data\":[";
    			for(int i = 0; i < list.size(); i++) {
    				String arr = "{";
    				for( int j = 0; j < list.get(0).length; j++) {
    					
    					if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
    						arr += "\"" + colums[j] + "\":\"\"";
    					}else {
    						arr += "\"" + colums[j] + "\""+":" ;
    						arr +=  "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
    					}
    					
    					if( j < list.get(0).length - 1 ) {
    						arr += ",";
    					}
    				}
    				arr += "}";
    				if( i < list.size() - 1 ) {
						arr += ",";
					}
    				
    				jsonStr += arr;
    			}
    			jsonStr += "]}";
    	
    	return jsonStr;
    }

}

3.3 AddServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/add")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name");
		String number = request.getParameter("num");
		String price = request.getParameter("price");
		String sql = "insert into commodity(name, num, price) VALUES ('"+ name + "', " + number + ", "+ price + ");";
		int num = MysqlUtil.add(sql);
		response.getWriter().write(num + "");
	}
}

3.4 CommodityServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class CommodityServlet
 */
@WebServlet("/commodity")
public class CommodityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CommodityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		//设置返回数据的格式
		response.setContentType("text/json;charset:utf-8");
		String sql = "select * from commodity";
		String[] column ={"id","name","num","price"};
		String res = MysqlUtil.getJsonBySql(sql, column);
		System.out.println(res);
		// 响应数据
		response.getWriter().write(res);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

3.5 DelectServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class DelectServlet
 */
@WebServlet("/del")
public class DelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DelectServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 接受参数
		String id = request.getParameter("id");
		String sql = "delete from commodity where id = " + id;
		int num = MysqlUtil.del(sql);
		response.getWriter().write(num);
	}

}

3.6 SelectByIdServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class SelectByIdServlet
 */
@WebServlet("/selectById")
public class SelectByIdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectByIdServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = request.getParameter("id");
		String sql = "select * from commodity where id ='" + id +"';";
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		//设置返回数据的格式
		response.setContentType("text/json;charset:utf-8");
		String[] column ={"id","name","num","price"};
		String res = MysqlUtil.getJsonBySql(sql, column);
		System.out.println(res);
		// 响应数据
		response.getWriter().write(res);
	}

}

3.7 SelectServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class SelectServlet
 */
@WebServlet("/select")
public class SelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = request.getParameter("name");
		String sql = "select * from commodity where name ='" + name +"';";
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		//设置返回数据的格式
		response.setContentType("text/json;charset:utf-8");
		String[] column ={"id","name","num","price"};
		String res = MysqlUtil.getJsonBySql(sql, column);
		System.out.println(res);
		// 响应数据
		response.getWriter().write(res);
	}

}

3.8 UpdataServlet.java

package com.qcby.servlet;

import java.io.IOException;
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 com.qcby.db.MysqlUtil;

/**
 * Servlet implementation class UpdataServlet
 */
@WebServlet("/updata")
public class UpdataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdataServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String number = request.getParameter("num");
		String price = request.getParameter("price");
		String sql = "update commodity set  name = '" + name + "', num = "+ number +", price="+ price +" where id = " + id +";";
		int num = MysqlUtil.update(sql);
		response.getWriter().write(num + "");
	}

}

3.9 style.css

*{
    margin: 0;
    padding: 0;
}
@font-face {
    font-family: YUZ;
    src: url(./YXZ.ttf);
}
body{
	position: relative;
	padding-top: 100px;
}
#todo {
    width: 500px;
    min-width: 500px;
    padding: 5px;
    background:linear-gradient(red,blue);
    background:-moz-linear-gradient(left,#ace,#f96);
    background:-webkit-gradient(linear,0 50%,100% 50%,from(#ace),to(#f96));
    background:-webkit-linear-gradient(left,#ace,#f96);
    background:-o-linear-gradient(left,#ace,#f96);
    margin: auto;
    border-radius: 10px;
    border: solid 1px wheat;
}
#todo .cmmodityName{
	width: 50%;
    height:25px;
    line-height:30px;
    border-radius: 10px 10px 10px 10px;
    border: solid 1px rgb(255, 255, 255);
    margin-bottom: 10px;
    padding-left: 10px;
    font-size: 20px;
}

#todo .add, #todo .select{
    width: 15%;
    height:30px;
    line-height:30px;
    border-radius: 10px 10px 10px 10px;
    background-color: rgb(39, 160, 225);
    border: solid 1px rgb(255, 255, 255);
    margin-bottom: 10px;
}
#todo #add{
    width: 40%;
    border-radius: 0px 10px 10px 0px;
    background-color: rgb(39, 160, 225);
    border: 0;
    cursor: pointer;
    color: rgb(255, 255, 255);
}
#todoList{
    width: 100%;
    border-radius: 10px;
    overflow: hidden;
    color: white;
}
#todoList thead {
    background-color: rgb(39, 160, 225);
}
#todoList thead td:first-child {
    width: 20%;
    border-radius: 10px 0px 0px 0px;
}
#todoList thead td:last-child {
    border-radius: 0px 10px 0px 0px;
}
#todoList tr{
    width: 100%;
    height: 40px;
    text-align: center;
    color: rgb(51, 51, 51);
}
#todoList td{
    border: solid 1px white ; 
}
#todoList tr td input{
    width: 45px;
    height: 25px;
    line-height: 25px;
    font-family: Arial, Helvetica, sans-serif;
    background-color: #ace;
    border: solid 1px white;
    color: rgb(67, 67, 67);
}
#todoList tr td input:first-child{
    border-radius: 5px 0 0 5px;
}
#todoList tr td input:last-child{
    border-radius: 0 5px 5px 0;
    border-left: 0;
}
#add_div, #add_div2{
	position: absolute;
	top: 0;
    left: 0;
    background-color: rgba(255, 255, 255, 0.95);
    width: 100%;
    height: 100vh;
}
#add_div .add_div{
    margin: auto;
    padding: 5px;
    border: solid 2px #ac0f0f;
    border-radius: 3px;
    position: absolute;
    width: 20%;
    height: 20%;
    top: 40%;
    left: 40%;
}
#add_div .add_div input{
    height: 20px;
    width: 150px;
    padding-left: 5px;
}
#add_div2 .add_div{
    margin: auto;
    padding: 5px;
    border: solid 2px #ac0f0f;
    border-radius: 3px;
    position: absolute;
    width: 20%;
    height: 20%;
    top: 40%;
    left: 40%;
}
#add_div2 .add_div tr th{
    width: 100px;
    height: 30px;
}
#add_div2 .add_div span{
    height: 20px;
    width: 100px;
    padding-left: 5px;
}
#add_div2 .add_div input{
    height: 20px;
    width: 200px;
}

3.10 index.js

// 初始化
$.ajax({
	url:"commodity",
	type: "get",
	success:function(value){
		console.log(value);
		var arr = value.data;
		for(let i = 0 ; i < arr.length; i ++){
			$("#one").append("<tr>" + 
				"<td>" + arr[i].name +"</td>"+
				"<td>" + arr[i].num +"</td>"+
				"<td>" + arr[i].price +"</td>"+
                "<td>" + "<input type=\"button\" value=\"修改\" class=\"reUpdata\" index = \"" + arr[i].id + "\">" + 
    			"<input type=\"button\" class = \"del\" value=\"删除\" index = \""+ arr[i].id +"\">" + "</td>")
		}
	},
	error:function(){
		alert("失败了!!");
	}
})
// 删除
$("tbody").on("click",".del", function(){
	var id = $(this).attr("index");
	$.ajax({
		url:"del",
		type:"post",
		data:{
			id
		},
		success:function(value){
			location.reload();
		},
		error: function(){
			alert("失败了!!");
		}
	})
})
var flag = 1;
// 点击添加
$(".add").on("click",function(){
	$("#add_div").css("display","block");
	$(".name").val("");
	$(".num").val("");
	$(".price").val("");
	$(".upData").val("添加商品");
	flag = 1;
})
// 点击取消
$(".back").on("click", function(){
	$("#add_div").css("display","none");
})
// 取消查找
$(".back2").on("click", function(){
	$("#add_div2").css("display","none");
})
// 点击查找
$(".select").on("click",function(){
	var name = $(".cmmodityName").val();
	if(name==""){
		alert("输入正确的格式!!!");
		return;
	}
	$.ajax({
		url:"select",
		type:"post",
		data:{
			name
		},
		success:function(value){
			if(value.data.length == 0){
				alert("不存在该物品");
				return;
			}
			var arr = value.data[0];
			$(".Cname").text(arr.name);
			$(".Cnum").text(arr.num);
			$(".Cprice").text(arr.price);
			$("#add_div2").css("display","block");
		},
		error:function(){
			alert("不存在该物品");
		}
	});
	
})
// 点击第二个添加,更新数据
$(".upData").on("click", function(){
	// 是1,就是添加
	if(flag ==1){
		var name = $(".name").val();
		var num = $(".num").val();
		var price = $(".price").val();
		$.ajax({
			url:"add",
			type:"post",
			data:{
				name,num,price
			},
			success:function(value){
				console.log(value);
				if(value=="0"){
					alert("请输入正确格式!!!");
				}else{
					location.reload();
					alert("添加成功!!!");
				}
			},
			error:function(){
				alert("失败了")
			}
		})
	}else{
		var id = $(".Cid").val();
		var name = $(".name").val();
		var num = $(".num").val();
		var price = $(".price").val();
		$.ajax({
			url:"updata",
			type:"post",
			data:{
				id, name, num, price
			},
			success:function(value){
				console.log(value);
				if(value=="0"){
					alert("请输入正确格式!!!");
				}else{
					location.reload();
					alert("修改成功!!!")
				}
			},
			error:function(){
				alert("失败了");
			}
		})
	}
})
// 点击修改
$("tbody").on("click",".reUpdata", function(){
	$("#add_div").css("display","block");
	id = $(this).attr("index");
	$.ajax({
		url:"selectById",
		type:"post",
		data:{
			id
		},
		success:function(value){
			flag = 0;
			var arr = value.data[0];
			$(".Cid").val(arr.id);
			$(".name").val(arr.name);
			$(".num").val(arr.num);
			$(".price").val(arr.price);
			$(".upData").val("修改");
		},
		error: function(){
			alert("失败了!!");
		}
	})
})

3.11 jquery-3.7.1.min.js(略)

3.12 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.7.1.min.js"></script>
    <script src="js/index.js" defer></script>
</head>
<body>
    <!-- <div>demo</div>
    <a href="test">你好</a> -->
    <div id="todo">
    商品名称:<input type="text" class="cmmodityName"><input type="button"  class="select" value="查找"><input type="button"  class="add" value="添加">
        <table id="todoList" cellpadding="0" cellspacing="0" >
            <thead>
                <td>商品名字</td>
                <td>数量</td>
                <td>价格</td>
                <td>操作</td>
            </thead>
            <tbody id ="one">
                
            </tbody>
        </table>
    </div>
    <div id="add_div" style="display:none">
        <table class="add_div">
            <tr>
                <th>商品名称:</th>
                <th><input type="text" class="name"></th>
            </tr>
            <tr>
                <th>商品数量:</th>
                <th><input type="text" class="num"></th>
            </tr>
            <tr>
                <th>商品价格:</th>
                <th><input type="text" class="price"></th>
            </tr>
            <tr>
                <th> <input type="button" value="添加" class="upData"></th>
                <th><input type="button" value="取消" class="back"></th>
            </tr>
        </table>
    </div>
    <div id="add_div2" style="display:none">
        <span class="Cid" style="display:none">1</span>
        <table class="add_div">
            <tr>
                <th>商品名称:</th>
                <th><span class="Cname">XXX</span></th>
            </tr>
            <tr>
                <th>商品数量:</th>
                <th><span class="Cnum">XXX</span></th>
            </tr>
            <tr>
                <th>商品价格:</th>
                <th><span class="Cprice">XXX</span></th>
            </tr>
            <tr>
                <th colspan="2"><input type="button" value="取消" class="back2"></th>
            </tr>
        </table>
    </div>
    
    
</body>
</html>

4. 效果展示

查找不存在的物品:
查找1
查找成功:
查找2
点击添加:
在这里插入图片描述

添加成功:
在这里插入图片描述
在这里插入图片描述

添加失败:
在这里插入图片描述

点击删除就直接没了

点击修改:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5. 链接

javaWeb项目创建

史上最全MySQL基本操作(这一篇就够用了!!!)

6. 思考

目前还是不完美的,当添加商品时,商品已经存在表里,仍然能添加上,就交给你去修改了。(因为我比较懒。。。。)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1617162.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2024 OceanBase 开发者大会:OceanBase 4.3正式发布,打造PB级实时分析数据库

4月20日&#xff0c;2024 OceanBase开发者大会盛大召开&#xff0c;吸引了50余位业界知名的数据库专家和爱好者&#xff0c;以及来自全国各地的近600名开发者齐聚一堂。他们围绕一体化、多模、TP与AP融合等前沿技术趋势展开深入讨论&#xff0c;分享场景探索的经验和最佳实践&a…

同旺科技 USB TO SPI / I2C适配器读写24LC256--字节写

所需设备&#xff1a; 1、USB 转 SPI I2C 适配器&#xff1b;内附链接 2、24LC256芯片 适应于同旺科技 USB TO SPI / I2C适配器升级版、专业版&#xff1b; 00地址写入一个字节数据AA&#xff0c;并读回验证&#xff1b; 单字节写时序&#xff1a; 读字节时序&#xff1a; …

架构师系列-MYSQL调优(七)- 索引单表优化案例

索引单表优化案例 1. 建表 创建表 插入数据 下面是一张用户通讯表的表结构信息,这张表来源于真实企业的实际项目中,有接近500万条数据. CREATE TABLE user_contacts (id INT(11) NOT NULL AUTO_INCREMENT,user_id INT(11) DEFAULT NULL COMMENT 用户标识,mobile VARCHAR(50…

2016年新华三杯复赛实验试题

2016年新华三杯复赛实验试题 拓扑图 配置需求 考生根据以下配置需求在 HCL 中的设备上进行相关配置。 以太网接口配置 将 S1、S2 的以太网接口 G1/0/1 至 G1/0/16 的模式用命令 combo enable copper 激活为电口。 虚拟局域网 为了减少广播&#xff0c;需要规划并配置 VLA…

Zabbix监控系统:基础配置及部署代理服务器

目录 前言 一、自定义监控内容 1、在客户端创建自定义key 2、在服务端验证新建的监控项 3、在web界面创建自定义监控项模版 3.1 创建模版 3.2 创建应用集&#xff08;用于管理监控项&#xff09; 3.3 创建监控项 3.4 创建触发器 3.5 创建图形 3.6 将主机与模板关联…

利用selenium发挥vip残存的价值

历史版本谷歌浏览器驱动下载地址 https://chromedriver.storage.googleapis.com/index.html 找到与你电脑当前谷歌浏览器版本一致的驱动然后下载下来(大版本一致即可)。我本地版本是 99.0.04844.51 我这里把 chromedriver 放到 /usr/local/bin 下面了。 启动测试窗口 这里需要…

【软件测试】认识测试|测试岗位|软件测试和开发的区别|优秀的测试人员需要具备的素质

一、什么是测试 测试在⽣活中处处可⻅ 1.生活中的测试场景 案例⼀&#xff1a;对某款购物软件进⾏测试 *启动测试&#xff1a;点击软件图标&#xff0c;测试软件是否可以正常打开 搜索测试&#xff1a;点击输入框&#xff0c;输入关键词&#xff0c;点击搜索 商品测试&#…

【Linux】IO多路转接技术Epoll的使用

【Linux】IO多路转接技术Epoll的使用 文章目录 【Linux】IO多路转接技术Epoll的使用前言正文接口介绍工作原理LT模式与ET模式边缘触发&#xff08;ET&#xff09;水平触发&#xff08;LT&#xff09; 理解ET模式和非阻塞文件描述符ET模式epoll实现TCP服务器简单地封装epoll系统…

python创建线程和结束线程

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 python创建线程和结束线程 在 Python 中&#xff0c;线程是一种轻量级的执行单元&#xff…

【C++学习】STL之空间配置器之一级空间配置器

文章目录 &#x1f4ca;什么是空间配置器✈STL 提供六大组件的了解&#x1f440;为什么需要空间配置器&#x1f44d;SGI-STL空间配置器实现原理&#x1f302;一级空间配置器的实现 &#x1f4ca;什么是空间配置器 空间配置器&#xff0c;顾名思义就是为各个容器高效的管理空间…

“五之链”第十六期沙龙活动在呆马科技成功举办

2024年4月19日&#xff0c;由临沂呆码区块链网络科技有限公司&#xff08;呆马科技&#xff09;承办的第十六期“五之链”物流主题沙龙活动成功举办。此次活动邀请了政府相关部门、知名科研院所、物流企业等20余家单位参与&#xff0c;共同探讨物流数据要素流通与智能应用的发展…

C语言----链表

大家好&#xff0c;今天我们来看看C语言中的一个重要知识&#xff0c;链表。当然大家可以先从名字中看出来。就是一些表格用链子连接。那么大家是否想到了我们以前学的数组&#xff0c;因为数组也是相连的呀。是吧。但是链表与数组还是有区别的&#xff0c;那么链表是什么有什么…

uniApp项目总结

前言 大半年的时间&#xff0c;项目从秋天到春天&#xff0c;从管理后台到APP再到数据大屏&#xff0c;技术栈从vue3到uniApp再到nuxt3&#xff0c;需求不停的改&#xff0c;注释掉代码都快到项目总体的三分之一。 一&#xff0c;项目技术栈分析 1.1 项目框架 当前&#xf…

树与二叉树的学习笔记

树与二叉树 在之前的学习中&#xff0c;我们一直学习的是一个线性表&#xff0c;数组和链表这两种都是一对一的线性表&#xff0c;而在生活中的更多情况我们要考虑一对多的情况&#xff0c;这时候就引申出了我的新的数据结构那就是树&#xff0c;而树经过一些规矩的指定也就成为…

秒懂图神经网络(GNN)

​ 图神经网络&#xff08;GNN&#xff09;是一种深度学习模型&#xff0c;专门为处理图结构数据而设计。在现实世界中&#xff0c;许多数据都可以通过图来表示&#xff0c;比如社交网络中人与人之间的联系、分子结构中的原子连接等。图由顶点&#xff08;或称为节点&#xff0…

LLM使用方法介绍,持续更新

LLM使用方法介绍&#xff0c;持续更新 1. LLM本地搭建与运行 1. Ollama的安装 网址&#xff1a;https://ollama.com/点击Download选择对应的操作系统下载安装软件&#xff0c;软件默认安装在C盘无法选择路径&#xff1b; 安装完成后&#xff0c;WinR进入终端执行&#xff1a…

推荐一个在线stable-diffusion-webui,通过文字生成动画视频的网站-Ai白日梦

推荐一个可以通过文字生成动画视频的网站&#xff0c;目前网站处于公测中&#xff0c;应该是免费的。 点击新建作品 使用kimi或者gpt生成一个故事脚本 输入故事正文 新建作品&#xff0c;选择风格 我这里显示了六个风格&#xff0c;可以根据自己需要选一个 选择配音&…

54、图论-实现Trie前缀树

思路&#xff1a; 主要是构建一个trie前缀树结构。如果构建呢&#xff1f;看题意&#xff0c;应该当前节点对象下有几个属性&#xff1a; 1、next节点数组 2、是否为结尾 3、当前值 代码如下&#xff1a; class Trie {class Node {boolean end;Node[] nexts;public Node(…

Java——三层架构

在我们进行程序设计以及程序开发时&#xff0c;尽可能让每一个接口、类、方法的职责更单一些&#xff08;单一职责原则&#xff09;。 单一职责原则&#xff1a;一个类或一个方法&#xff0c;就只做一件事情&#xff0c;只管一块功能。 这样就可以让类、接口、方法的复杂度更低…

centos7上搭建mongodb数据库

1.添加MongoDB的YUM仓库&#xff1a; 打开终端&#xff0c;执行以下命令来添加MongoDB的YUM仓库&#xff1a; sudo vi /etc/yum.repos.d/mongodb-org-4.4.repo 在打开的文件中&#xff0c;输入以下内容&#xff1a; [mongodb-org-4.4] nameMongoDB Repository baseurlh…