Java desktop program: load data-fuzzy query-delete-add

1.DB.java
2.BaseDao.java
3. Two forms
insert image description here
insert image description here

1. DB.java

full code

package dao;

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

public class DB {
    
    
	static{
    
    
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}
	}
	
	public static Connection getConn() throws SQLException{
    
    
		return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shangpin?characterEncoding=utf-8",
				"root", "1234");
	}
	
	public static void closeAll(Connection conn){
    
    
		if(conn !=null){
    
    
			try {
    
    
				conn.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws SQLException {
    
    
		System.out.println(getConn());
	}
	
}

2. BaseDao.java

full code

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
    
    
	static Connection conn;
	static PreparedStatement pst;
	static ResultSet rs;

	// 查询
	public static ResultSet cx(String sql) {
    
    

		try {
    
    
			conn = DB.getConn();
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		return rs;
	}

	// 增删改
	public static boolean zsg(String sql) {
    
    

		try {
    
    
			conn = DB.getConn();
			pst = conn.prepareStatement(sql);
			return pst.executeUpdate() > 0;
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			DB.closeAll(conn);
		}
		return false;
	}
}

3. Part of the code in the two forms :

① When the program starts to execute, it needs to load the display data:
In the main form - modify the code in the constructor

/** 修改构造器,增加添加调用语句 */
	public ZhuYe() {
    
    
		initComponents();
		
		//在构造器中增加调用初始表格的方法
		initTable("select * from tb_goods");
	}

② Define the method of initializing the form:
in the main form - complete code

//初始化表格的方法
	private void initTable(String sql) {
    
    
		//1.准备好所有的数据,放入 data 中
		Vector data = new Vector(); 
		
		ResultSet rs = BaseDao.cx(sql); //查询数据库
		try {
    
    
			while (rs.next()) {
    
    
				Vector line = new Vector(); // line 代表存放一行数据的集合
				int id = rs.getInt("goodId");
				String name = rs.getString("goodName");
				int num = rs.getInt(3);
				double pric = rs.getDouble(4);
				line.add(id);
				line.add(name);
				line.add(num);
				line.add(pric);

				data.add(line); //将当前行存入大的data中
			}
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		
		//2.准备好标题文字,放入 bt 中
		Vector bt = new Vector(); //bt 用于存放标题
			bt.add("商品编号");
			bt.add("商品名字");
			bt.add("商品数量");
			bt.add("商品价格");

		//3.最终任务就是用上面准备好的 数据 和 标题 填充 表格
		jTable1.setModel(new DefaultTableModel(data, bt));
	}

③ Operation when the query button is clicked—fuzzy query:
insert image description here
complete code—write in the main form

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    
    
		// 点击查询按钮要完成的工作:
		//1.获取文本框的内容
		String text = wbk.getText();
		
		//2.拼接出一个模糊查询的sql语句
		//select * from tb_goods where goodName like '%鼠标%'
		String sql = "select * from tb_goods where goodName like '%" + text + "%'";

		//3.调用初始化表格的方法
		initTable(sql);
	}

④ Realize the function of the delete button:
delete function
complete code - written in the main form

/* 点击删除按钮时:
	 * 1.判断是否选中了某一行,如果没选中,则给出提示:"您未选择任何数据"
	 * 2.如果选中了某一行,则给出确认提示以防止误删除,"您确定要删除吗?",点击确定返回0,点击取消返回1。
	 * 3.执行删除:找到对应的行号---获取id---根据id组装sql语句---执行删除
	 * */
	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    
    

		int rowCount = jTable1.getSelectedRowCount(); //获取选中的行数,如果为0,则说明没有选中任何行
		if (rowCount == 0) {
    
    
			JOptionPane.showMessageDialog(null, "您未选择任何数据");
		} else {
    
    
			int isOk = JOptionPane.showConfirmDialog(null, "您确定要删除吗?", "删除确认",
					JOptionPane.YES_NO_OPTION);
			//			System.out.println(isOk);
			if (isOk == 0) {
    
     //如果值是 0 ,说明点击了确定要删除
				int selectedRow = jTable1.getSelectedRow();  //获取选中行的索引
				int id = (Integer) jTable1.getModel()
						.getValueAt(selectedRow, 0); //找到要删除的行的第一列,其实就是要删除的商品的编号
				String sql = "delete from tb_goods where goodid=" + id; //拿到商品编号后,组装出删除的sql语句
				boolean zsg = BaseDao.zsg(sql); //执行删除操作,并返回是否成功
				if (zsg) {
    
    
					JOptionPane.showMessageDialog(null, "删除成功!");
					
					//删除后,调用表格初始化的方法,重新加载数据,使表格加载显示最新数据:
					initTable("select * from tb_goods");  
				} else {
    
    
					JOptionPane.showMessageDialog(null, "删除失败!");
				}
			}
		}
	}

⑤ Add a new product (write on the new button in the new product form). Note
in the new product
: After the addition is completed, return to the main interface and automatically refresh the data on the main interface. You need to modify the previous code
New product interface
Complete code - in the new Write in the form of adding products

	// 新增商品的处理过程:
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    
    

		// 1. 获取所有文本框的数据
		String idtext = tx1.getText().trim();   //tx1是第一个文本框的名字(改名了)
		String name = tx2.getText().trim();
		String numtext = tx3.getText().trim();
		String pricetext = tx4.getText().trim();
		
		//2.如果有没填写的文本框,则给出提示
		if ("".equals(idtext) || "".equals(name) || "".equals(numtext)
				|| "".equals(pricetext)) {
    
    
			JOptionPane.showMessageDialog(null, "请录入完整信息!");
		} 
		//3.如果所有的文本框都填写了,则进行插入操作:
		else {
    
    
		//准备并拼装新增sql语句,首先将文本框获取到的字符串 转换为数据库表中相对应的数据类型
			int id = Integer.parseInt(idtext);
			int num = Integer.parseInt(numtext);
			double pri = Double.parseDouble(pricetext);
			
			//拼装sql新增语句:
			String sql = String.format("insert into tb_goods values(%d,'%s',%d,%f)", id, name,num, pri);
			
			if (BaseDao.zsg(sql)) {
    
      	//真正的执行,并根据返回结果给出提示
				
				JOptionPane.showMessageDialog(null, "新增商品成功!");
				// this.setVisible(false); //隐藏当前窗体
				this.dispose(); // 销毁挡墙窗体

				// 下面这一行是,自动刷新主页面,重新加载数据(根据考试要求进行编写,还需要修改其他地方,详见后面的**备注**)
				// 注意:在主窗体中的 initTable 方法定义,需要由 private 改为 public,否则无法访问!!
				// mp.initTable("SELECT * FROM tb_goods");  //mp:为主页窗体对象,在前面进行了定义。**详细在下面描述**
			}
			else{
    
    
				JOptionPane.showMessageDialog(null, "新增商品失败!");
			}
		}
	}

The following content is optional to view and read, which is related to refreshing and loading the home page data after adding products. (You can master the above content first, and practice the following content after the above content is proficient)
Remarks : To realize the function of automatically refreshing the main form after the addition is completed, the places that need to be modified:

①In the new product form:
write the code at the top of the new form. Declare and define a variable of the main form to accept the main form object; create a constructor with parameters to create a new form object in the main form, and pass the
core code - in the new form write:

public class Add extends javax.swing.JFrame {
    
    

	//声明一个主窗体类型的属性
	MainPage mp;

	/** Creates new form Add */
	public Add() {
    
    
		initComponents();
	}

	//写一个带参数的构造器,给上面声明的主窗类型的变量体赋值
	public Add(MainPage mp) {
    
    
		initComponents();
		this.mp = mp; //给上面声明的主窗类型的变量体赋值
	}

②In the main form:
write code in the main form. When you click the button to add new products and open the new product form, add this form to the
complete code of the new product form - write in the main form

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    
    
		//将本窗体(主窗体)this 作为参数,传递给 添加商品的窗体,以便添加完商品后操作主窗体更新数据
		Add add = new Add(this);  
		add.setVisible(true);
	}

Guess you like

Origin blog.csdn.net/weixin_42634814/article/details/131132580