Programmer Help

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 30

Programmer Help

Home Blogs Tags

java supermarket shopping management system

I. overview

1. Peng GE has written java project supermarket management system project in front of him, Portal

2. received many friends' personal letters to me, and I also appreciated the feedback and
communication from the old fellow. The previous project was just a basic knowledge and object-
oriented thinking exercise for java, but it didn't involve how java manipulate the database, how to get
data out of the database through java, and save these problems. For java novices, they don't know
where to start. There are a lot of new java novices suggest that I write a practical project of java
operation database for the reference of the entrants. I think if I can help them spend less time out of the
pit, why not? Peng Ge took the exam for a day, sorted out his ideas, and today took the time to write a
supermarket shopping management system..... go go go

3. Knowledge involved in the supermarket shopping management system: java basic syntax, java object-
oriented development ideas, how Java operates the database, knowledge of collection

4. Suitable for java beginners, do not know how Java operates the database

5. Basically all codes will be annotated for easy reading

6. Because it is a practical project of java operating database, it will not explain the knowledge of java
environment construction, database installation and sql syntax in detail. Too much. I can't finish it in a
week... Or I can go to pengge station java 1 View related articles. So before you start, you should install
the java development environment, the database

7. The development tool eclipse; jdk is 1.8; the database uses mysql5.5 (of course, the SQL Server
database is OK)
8. source code acquisition: I will paste out the core code, all code attention will be given to Peng Peng
public number java actual combat project.

II. Effect demonstration

=================Welcome to the supermarket shopping management system=================

1. Goods warehousing

2. Query commodities according to commodity number

3. Commodity list

4. Purchase of goods

5. Delete goods

6. Update goods

0. Exit the system

Please enter the action to be performed

No. Name unit price quantity

1234 Apple 12.0 35

1235 clothes 123.0 0

1236 basketball 200.0 20

Enter y to continue / otherwise exit

1. Goods warehousing

2. Query commodities according to commodity number

3. Commodity list

4. Purchase of goods

5. Delete goods
0. Exit the system

Please enter the action to be performed

Enter the purchase item number

1235

Enter quantity of goods purchased

This product inventory 0 cannot be purchased;

Enter y to continue purchasing / enter other settlement

Enter the purchase item number

1234

Enter quantity of goods purchased

Purchase success

Enter y to continue purchasing / enter other settlement

1236

No.? Name? Quantity? Total price

1234 Apple 2 24.0

Total consumption: 24.0 yuan

Enter y to continue / otherwise exit

1. Goods warehousing

2. Query commodities according to commodity number

3. Commodity list
4. Purchase of goods

5. Delete goods

0. Exit the system

Please enter the action to be performed

Enter item number to delete

4564

There is no such product

Enter y to continue / otherwise exit

1. Goods warehousing

2. Query commodities according to commodity number

3. Commodity list

4. Purchase of goods

5. Delete goods

0. Exit the system

Please enter the action to be performed

No. Name unit price quantity

1234 Apple 12.0 33

1235 clothes 123.0 0

1236 basketball 200.0 20

Enter y to continue / otherwise exit

1. Goods warehousing
2. Query commodities according to commodity number

3. Commodity list

4. Purchase of goods

5. Delete goods

0. Exit the system

Please enter the action to be performed

Enter the purchase item number

1234

Enter quantity of goods purchased

Purchase success

Enter y to continue purchasing / enter other settlement

Enter the purchase item number

1234

Enter quantity of goods purchased

Purchase success

Enter y to continue purchasing / enter other settlement

No.? Name? Quantity? Total price

1234 Apple 4 48.0

Total consumption: 48.0 yuan

Enter y to continue / otherwise exit


III. create project

Create a ShopManager project in eclipse

Next, we introduce the database driven jar package, which can be downloaded from the official website
or can be obtained from my public address java reply jdbc.

What does java have to do with this database driver? The simple understanding is that this database
driver is the bridge between Java and database, which is used for communication between them.

Create a folder for lib

Copy our prepared driver to this lib

Right click on this driver to execute


Last complete structure

It's very important, very important, very important to create the project structure. These are the things
that we should pay attention to in development. For these small projects, we can put all the code classes
under src. But later, the project is getting larger and larger. There are hundreds of all classes in src.
Without subcontracting, other developers of the project can see how much damage the code bears.

This system is relatively simple. The following four packages can be used. The app package is used to put
the main entry class of the system, the entity class involved in the pojo system, the service system
business, the tool class in the utils system, and the test temporary test class

4. Connect to the database

Because the system will involve multiple access to the data in the database, we will write a tool class
DbUtil for the operation of connecting the database, and do not write repeated connection codes every
time it involves the operation of the database.

package com.javayihao.top.utils;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

/**

* @date 2019-12-9

* @Description Connection database tool class

* @author com.javayihao.top

*/

public class DbUtil {

//Several strings used to connect to the database are defined as constants, which need not be
created every time

private static final String USER = "root";//Database user name

private static final String UPWD = "root";//Database password

//Local database shop

private static final String URL = "jdbc:mysql://localhost:3306/shop";

//drive

private static final String DRIVER = "com.mysql.jdbc.Driver";

//Registration driven

static {

try {

Class.forName(DRIVER);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}
//Get the function of database Connection object Connection

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(URL, USER, UPWD);

//Close connected and executed open resources

public static void close(Connection connection, Statement statement) {

if (statement != null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

if (connection != null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

//Close all open resources

public static void close(Connection connection, Statement statement, ResultSet rs) {


if (statement != null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

if (connection != null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

test
package com.javayihao.top.test;

import java.sql.Connection;

import java.sql.SQLException;

import com.javayihao.top.utils.DbUtil;

/**

* @date 2019-12-9

* @Description Test database connection class

* @author com.javayihao.top

*/

public class DbUtilTest {

public static void main(String[] args) throws SQLException {

Connection con = DbUtil.getConnection();

System.out.println(con);

The database connection is successful as follows

V: create entity class

package com.javayihao.top.pojo;
/**

* @date 2019-12-9

* @Description Commodity entity

* @author com.javayihao.top

*/

public class Good {

//Commodity number

private int id;

//Trade name

private String name;

//Commodity price (the price may involve a small number, and float is used here. Of course, the
real large shopping platform will not use float, and interested friends can learn about it online)

private float price;

//Stock

private int num;

//Empty parameter structure

public Good() {

super();

//Printing method

@Override

public String toString() {

return "Good [id=" + id + ", name=" + name + ", price=" + price + ", num=" + num + "]";

//Parametric construction, easy to initialize objects

public Good(int id, String name, float price, int num) {


super();

this.id = id;

this.name = name;

this.price = price;

this.num = num;

//set get method

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getPrice() {

return price;

public void setPrice(float price) {

this.price = price;

}
public int getNum() {

return num;

public void setNum(int num) {

this.num = num;

Six: Database

Create a database shop locally and create a table T "good"

CREATE TABLE `t_good` (

`id` int(5) NOT NULL,

`name` varchar(25) NOT NULL,

`price` float(10,2) NOT NULL,

`num` int(5) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

VII. Core business

package com.javayihao.top.service;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Scanner;

import com.javayihao.top.pojo.Good;

import com.javayihao.top.utils.DbUtil;

/**

* @date 2019-12-9

* @Description System main interface

* @author com.javayihao.top

*/

public class ShopView {

//Get keyboard input object

Scanner input = new Scanner(System.in);

/*

* System operation method

*/

public void ShopStart() {

System.out.println("=================Welcome to the supermarket shopping


management system=================");

//Flag quantity whether to continue, default is

String isGo="y";

do{

//Call the function shown in the menu

showMenu();

System.out.println("Please enter the action to be performed");


//Accept the input from the keyboard. Use String here to process the
number and character input at one time. It is not recommended to use int type numbers

String select =input.next();

//Execute the corresponding method according to the input selection

switch (select) {

//Execute goods warehousing method

case "1":

insertGood();

break;

//Execute commodity query method

case "2":

System.out.println("Enter the item number to query");

int goodId = input.nextInt();

//Call the method to query the product,

Good good = searchGoodById(goodId);

//existence

if(good!=null){

System.out.println("Commodity number:"+goodId+"
Trade name:"+good.getName()

+" commodity price:"+good.getPrice()+" Quantity of


commodities:"+good.getNum());

}else{

System.out.println("This product does not exist");

break;

//Execute product list method

case "3":
getGoodList();

break;

//Execute commodity purchase method

case "4":

buyGood();

break;

//Execute commodity purchase method

case "5":

System.out.println("Enter item number to delete");

int id = input.nextInt();

//Call the method to query the product,

if(searchGoodById(id)!=null){

deleteGood(id);

}else{

System.out.println("There is no such product");

break;

case "6":

updateGood();

break;

//Exit system

case "0":

System.out.println("*************Welcome to the next use


bye!*************");

//Termination procedure

System.exit(0);
default:

System.err.println("Wrong input, please input again!");

continue;

System.out.println("input y Continue/Otherwise quit");

isGo = input.next();

}while(isGo.equals("y"));

System.out.println("*************Welcome to the next use bye!*************");

/**

* Update product action

* 1.First query whether the current product inventory to be updated does not exist

* 2.If there is an update, there is no prompt

*/

private void updateGood() {

System.out.println("Enter the item to modify id");

int gid = input.nextInt();

Good good = searchGoodById(gid);

System.out.println("The product information is as follows");

if(good!=null){

System.out.println("Commodity number:"+gid+" Trade name:"+good.getName()

+" commodity price:"+good.getPrice()+" Quantity of


commodities:"+good.getNum());

System.out.println("Modify product name");

String name = input.next();

System.out.println("Modify commodity unit price");


float price = input.nextFloat();

System.out.println("Modify commodity inventory");

int num = input.nextInt();

String sql="update t_good set name=?,price=?,num=? where id=? ";

try {

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an execution object PreparedStatement to execute sql

PreparedStatement pst = con.prepareStatement(sql);

//Set values for placeholders

pst.setString(1, name);

pst.setFloat(2, price);

pst.setInt(3, num);

pst.setInt(4, gid);

//execute() returns true if it is a query or false if it is an update or insert

if(!pst.execute()){

System.out.println("Update success");

//Close connection

DbUtil.close(con, pst);

} catch (Exception e) {

e.printStackTrace();

System.out.println("Update exception"+e.getMessage());

}else{
System.out.println("This product does not exist");

//Method for displaying system interface menu

private void showMenu() {

System.out.println("1.Goods warehousing");

System.out.println("2.Query products according to product number");

System.out.println("3.List of commodities");

System.out.println("4.Purchase goods");

System.out.println("5.Delete merchandise");

System.out.println("6.Update commodity");

System.out.println("0.Exit system");

/*

* Delete merchandise

* 1.First of all, we have to judge the existence of the commodity

* 2.Delete according to item id

*/

private void deleteGood(int id) {

String sql = "delete from t_good where id=?";

try {

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an execution object PreparedStatement to execute sql


PreparedStatement pst = con.prepareStatement(sql);

//Set values for placeholders

pst.setInt(1, id);

//execute() returns true if it is a query or false if it is an update or insert

if(!pst.execute()){

System.out.println("Delete successful");

//Close connection

DbUtil.close(con, pst);

} catch (Exception e) {

e.printStackTrace();

System.out.println("Delete exception"+e.getMessage());

/*

* Goods warehousing

* Here we only deal with the logic that the number cannot be repeated,

* As for whether the input number is a number, there is no judgment here. Interested friends
can try it

*/

private void insertGood(){

//Commodity number

int id=0;

System.out.println("Enter item number");

while(true){

id= input.nextInt();
//Judge whether the number entered is duplicate or not, and re-enter it
repeatedly

if(searchGoodById(id)==null){

break;

System.err.println("Duplicate number, please re-enter product number");

System.out.println("Enter product name");

String name = input.next();

System.out.println("Enter unit price of goods");

float price = input.nextFloat();

System.out.println("Enter item quantity");

int num = input.nextInt();

//To execute the sql statement, use placeholders here to prevent sql intrusion

String sql = "insert into t_good()values(?,?,?,?)";

try {

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an execution object PreparedStatement to execute sql

PreparedStatement pst = con.prepareStatement(sql);

//Set values for placeholders

pst.setInt(1, id);

pst.setString(2, name);

pst.setFloat(3, price);

pst.setInt(4, num);

//Execute sql statement


if(!pst.execute()){

System.out.println("Warehousing success");

//Close connection

DbUtil.close(con, pst);

} catch (Exception e) {

e.printStackTrace();

System.out.println("Abnormal storage"+e.getMessage());

/*Commodity inquiry

* The returned object is a product object. If there is no such product, null will be returned

*/

private Good searchGoodById(int id) {

//Executed sql statement

String sql="select id,name,price,num from t_good where id=?";

try {

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an object PreparedStatement to execute sql

PreparedStatement pst = con.prepareStatement(sql);

pst.setInt(1, id);

ResultSet rs = pst.executeQuery();

if(rs.next()){//As a result, the queried data is encapsulated into a commodity


object through the constructor

Good good = new Good(rs.getInt("id"), rs.getString("name"),


rs.getFloat("price"), rs.getInt("num"));

return good;

//Close connection

DbUtil.close(con, pst);

} catch (SQLException e) {

e.printStackTrace();

return null;

//List of commodities

private void getGoodList(){

//Executed sql statement

String sql="select id,name,price,num from t_good";

try {

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an object PreparedStatement to execute sql

PreparedStatement pst = con.prepareStatement(sql);

ResultSet rs = pst.executeQuery();

System.out.println("number\t"+"Name\t"+"Unit
Price\t"+"Number\t");

if(rs.wasNull()){

System.out.println("No goods");

}else{

while(rs.next()){//Results, printing
//Through rs.getxxx("yy") method parameter is
the database column name

System.out.println(rs.getInt("id")
+"\t"+rs.getString("name")+"\t"+

rs.getFloat("price")
+"\t"+rs.getInt("num")+"\t");

//Close connection

DbUtil.close(con, pst);

} catch (SQLException e) {

e.printStackTrace();

//Purchase goods

public void buyGood() {

//Collection used to store purchased items

ArrayList<Good> goods = new ArrayList<>();

//Do you want to continue to purchase the tag

String flag = "y";

do{

System.out.println("Enter the purchase item number");

int id = input.nextInt();

Good good = searchGoodById(id);

if(good!=null){

System.out.println("Enter quantity of goods purchased");

int num = input.nextInt();


if(good.getNum()<num){

System.out.println("This product inventory"+good.getNum()+"


Unable to purchase;");

}else{

try{

String sql="update t_good set num=? where id=?";

//Create an object to operate the database

Connection con = DbUtil.getConnection();

//Create an object PreparedStatement to execute sql

PreparedStatement pst = con.prepareStatement(sql);

pst.setInt(1, good.getNum()-num);//Update stock

pst.setInt(2, id);

if(pst.executeUpdate()==1){

//Set goods stored in the purchased goods

Good g = new
Good(id,good.getName(),good.getPrice(),num);

if(goods.size()>0){

for (int i = 0; i < goods.size(); i++) {

if(goods.get(i).getId()==id){//If
the shopping cart has the product quantity plus

goods.get(0).setNum(num+goods.get(0).getNum());

}else{//If there is no quantity


plus in the shopping cart

goods.add(g);

}
}

}else{//There is no item in the shopping cart,


add it to the shopping cart

goods.add(g);

System.out.println("Purchase success");

}else{

System.out.println("Purchase failure");

}catch(Exception e){

e.printStackTrace();

System.out.println("Purchase
exception"+e.getMessage());

System.out.println("input y Continue to buy/Enter other settlement");

flag = input.next();

if(!flag.equals("y")){

//Settlement

account(goods);

}else{

System.out.println("There is no such product");

}while(flag.equals("y"));

}
//Checkout cart

private void account(ArrayList<Good> goods) {

System.out.println("number\t"+"Name\t"+"Number\t"+"Total price");

//lambda expression traverses the collection. Of course, it is ok to use for loop

goods.forEach(in->System.out.println(in.getId()+"\t"+in.getName()+

"\t"+in.getNum()+"\t"+in.getNum()*in.getPrice()));

//Total

float sum=0;

for (int i = 0; i < goods.size(); i++) {

//Sum total price

sum += (goods.get(i).getNum())*(goods.get(i).getPrice());

System.out.println("Aggregate consumption:"+sum+"element");

summary

So far, the project has been completed, of course, there are still shortcomings in the project itself, for
example, in accepting the legitimacy judgment of keyboard input. For java operation database, you can
refer to,

I put the source code in the public number java No. 1, I need to mention it.

I hope your program will never be bug free


Tags: Java Database SQL JDBC

Posted on Tue, 10 Dec 2019 21:42:38 -0500 by YappyDog

facebook sharing button

twitter sharing button

reddit sharing button

linkedin sharing button

sharethis sharing button

Hot Tags

Java - 6272

Attribute - 2963

Programming - 2894

Database - 2805

Python - 2462

Spring - 2314

Javascript - 2287

xml - 2256

JSON - 2139

less - 2131

network - 2064

Android - 2061

github - 2047

Linux - 1810

MySQL - 1546
PHP - 1510

SQL - 1489

encoding - 1360

Mobile - 1172

Apache - 1114

©2021 Programmer Help Contact Us

You might also like