2024-12-19 初始化仓库

This commit is contained in:
JRNitre 2024-12-19 17:47:38 +08:00
commit 69cc12f920
25 changed files with 2835 additions and 0 deletions

29
.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

13
.idea/encodings.xml generated Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/ElmAdminEntry.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/ElmBusinessEntry.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/View/AdminView.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/View/BusinessView.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/View/Display.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/dao/AdminDaoImpl.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/dao/BusinessDaoImpl.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/jdbc/JDBC.java" charset="GBK" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,dao.AdminDaoImpl,fuzzyQueryExampleForName" />
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="mysql-connector-j-8.4.0">
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/mysql-connector-j-8.4.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

6
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/CourseExperiment.iml" filepath="$PROJECT_DIR$/CourseExperiment.iml" />
</modules>
</component>
</project>

124
.idea/uiDesigner.xml generated Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

12
CourseExperiment.iml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="mysql-connector-j-8.4.0" level="project" />
</component>
</module>

Binary file not shown.

104
src/ElmAdminEntry.java Normal file
View File

@ -0,0 +1,104 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
import View.AdminView;
import View.Display;
import po.Admin;
public class ElmAdminEntry {
public static void main(String[] args){
new ElmAdminEntry().work();
}
// CodeLineNum 2600
private static final int exitCode = 10;
public void work(){
Display dis = new Display('+', '-', 30);
AdminView adv = new AdminView();
// Admin admin = new Admin();
// admin.setAdminName("jrnitre");
// admin.setAdminId(1);
// admin.setAdminPassword("1234");
// 实例化管理员对象, 调用登录方法对其初始化
Admin admin = new AdminView().login();
if (admin != null){
int key;
while (true){
dis.titleLine("Admin - " + admin.getAdminName(), true);
dis.showItem("[0] 所有商家列表", true);
dis.showItem("[1] 搜索商家", true);
dis.showItem("[2] 新建商家", true);
dis.showItem("[3] 删除商家", true);
dis.showItem("[4] 查看管理员信息", true);
dis.showItem("[5] 设置管理员密码", true);
dis.showItem("[6] 查看管理员列表 (DEBUG)", true);
dis.showItem("[7] 查看所有食品列表 (DEBUG)", true);
dis.showItem("[" + exitCode + "] 退出系统", true);
dis.showLine(true);
// 获取操作数
key = dis.getKeyNumber();
// 判断用户操作
switch (key){
// 所有商家列表
case 0:
adv.printAllBusinessInfo();
break;
// 搜索商家
case 1:
adv.searchBusiness();
break;
// 新建商家
case 2:
adv.adminAddBusiness();
break;
// 删除商家
case 3:
adv.deleteBusiness();
break;
// 显示管理员信息
case 4:
adv.printAdminInfo(admin);
break;
// 设置管理员密码
case 5:
adv.updatePassword(admin);
break;
// 查看管理员列表
case 6:
adv.printAllAdminInfo();
break;
// 查看所有食品列表
case 7:
adv.printAdminAllFoodInfo();
break;
// Exit system
case exitCode:
if (dis.MessageYesOrNo("提示", "是否确定退出系统?")) {
dis.titleLine("提示", true);
System.out.println("+ 系统退出");
System.exit(0);
}
break;
// :-)
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
} else {
dis.titleLine("ERROR", true);
System.out.println("+ 错误次数过多! 退出系统");
System.exit(0);
}
}
}

130
src/ElmBusinessEntry.java Normal file
View File

@ -0,0 +1,130 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
import View.Display;
import View.BusinessView;
import po.Business;
public class ElmBusinessEntry {
public static void main (String[] args){
new ElmBusinessEntry().work();
}
private static final int exitCode = 10;
public void work(){
Display dis = new Display('+', '-', 30);
BusinessView buv = new BusinessView();
// Login 方法登录系统
Business business = new BusinessView().login();
// Business business = new Business();
// business.setBusinessPassword("1234");
// business.setBusinessName("business");
// business.setBusinessId(1);
// business.setBusinessAddress("null");
// business.setBusinessExplain("null");
// business.setBusinessStarPrice(5);
// business.setBusinessDeliveryPrice(1.5);
if (business != null){
int key;
while (true){
dis.titleLine("Business - " + dis.deleteSpaceToString(business.getBusinessName()), true);
dis.showItem("[0] 查看商家信息", true);
dis.showItem("[1] 修改商家信息", true);
dis.showItem("[2] 修改商家密码", true);
dis.showItem("[3] 管理食品信息", true);
dis.showItem("[" + exitCode + "] 退出系统", true);
dis.showLine(true);
key = dis.getKeyNumber();
switch (key){
// 查看商家信息
case 0:
buv.printBusinessInfo(business);
break;
// 修改商家信息
case 1:
buv.updateBusinessInfo(business);
break;
// 修改商家密码
case 2:
buv.updatePassword(business);
break;
// 管理食品信息
case 3:
food_work(business);
break;
case exitCode:
if (dis.MessageYesOrNo("提示", "是否确定退出系统?")) {
dis.titleLine("提示", true);
System.out.println("+ 系统退出");
System.exit(0);
}
break;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
} else {
dis.titleLine("ERROR", true);
System.out.println("+ 错误次数过多! 退出系统");
System.exit(0);
}
}
public void food_work(Business business){
Display dis = new Display('+', '-', 30);
BusinessView buv = new BusinessView();
int key;
while (true){
dis.titleLine("商家食品管理", true);
dis.showItem("[0] 查看食品列表", true);
dis.showItem("[1] 添加食品", true);
dis.showItem("[2] 修改食品信息", true);
dis.showItem("[3] 删除食品", true);
dis.showItem("[" + exitCode + "] 返回上级菜单", true);
key = dis.getKeyNumber();
switch ( key ){
// 查看食品列表
case 0:
buv.printAllBusinessFoodInfo(business);
break;
// 添加食品
case 1:
buv.addBusinessNewFood(business);
break;
// 修改食品信息
case 2:
buv.updateBusinessFoodInfo(business);
break;
// 删除食品
case 3:
buv.deleteFood(business);
break;
case exitCode:
if (dis.MessageYesOrNo("提示", "确定返回上级菜单?")) {
return;
}
break;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
}
}

558
src/View/AdminView.java Normal file
View File

@ -0,0 +1,558 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package View;
import dao.AdminDaoImpl;
import dao.BusinessDaoImpl;
import po.Admin;
import po.Business;
import java.sql.ResultSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Pattern;
public class AdminView {
Display dis = new Display('+', '-', 30);
/**
* 管理员登录方法
* 通过 Scanner 从标准输入获取管理员的用户名或ID和密码尝试进行登录
* 如果管理员输入的用户名或ID和密码匹配成功则返回对应的管理员对象否则允许管理员尝试多次登录直到尝试次数用尽
*
* @return 成功登录时返回管理员对象否则返回 null
*/
public Admin login(){
Scanner sca = new Scanner(System.in);
// 当前错误次数
int mistake = 0;
// 用户可以的最大错误次数
int maxMistake = 3;
// 登录状态机
int loginCode;
Admin admin = null;
while (mistake < maxMistake){
dis.titleLine("登录 [饿了么] 管理员后台", true);
// 错误次数大于 1 输出文字提醒用户
if (mistake != 0){
System.out.println("+ 密码输入错误 " + mistake + " 次 剩余可尝试次数 " + (maxMistake - mistake) + "");
}
// String 形式接收用户输入的 Id 名称
String inputAdminNameOrId;
// 登录 Id 初值 -1
int inputAdminId = -1;
System.out.print("+ 账户&Id: ");
inputAdminNameOrId = sca.nextLine();
// 判断用户输入的是字符串还是纯数字
// 分别调用不同的方法执行登录
try{
inputAdminId = Integer.parseInt(inputAdminNameOrId);
loginCode = 0;
} catch (NumberFormatException e){
loginCode = 1;
}
// 获取用户输入的密码
String inputAdminPassword;
System.out.print("+ 密码: ");
inputAdminPassword = sca.nextLine();
System.out.println("+ 登录系统中...");
if (loginCode == 0){
admin = new AdminDaoImpl().getAdminByIdByPass(inputAdminId, inputAdminPassword);
}
if (loginCode == 1){
admin = new AdminDaoImpl().getAdminByNameByPass(inputAdminNameOrId, inputAdminPassword);
}
if (admin != null){
return admin;
} else {
mistake++;
}
}
return null;
}
/**
* 更新管理员密码
* 该方法提供了一个交互式的界面用于管理员验证当前密码并设置新密码
* 它确保了新密码的正确性和安全性长度至少为10个字符
*
* @param admin 管理员对象包含当前管理员信息
*/
public void updatePassword(Admin admin){
// 创建临时管理员对象接收更改密码期间的用户输入
Admin tempAdmin = new Admin(admin);
dis.titleLine("更改密码", true);
while (true){
// 引导用户输入原来的密码
Scanner sca = new Scanner(System.in);
String afterAdminPassword;
System.out.print("+ 输入原密码: ");
afterAdminPassword = sca.nextLine();
// 判断新旧密码是否相等
if (afterAdminPassword.equals(tempAdmin.getAdminPassword())){
System.out.println("+ 密码正确");
while (true){
String newAdminPassword;
// 两次输入密码确保用户不会误输入
while (true){
String againNewAdminPassword;
System.out.print("+ 输入新密码 (10个字符): ");
newAdminPassword = sca.nextLine();
System.out.print("+ 再次新密码 (10个字符): ");
againNewAdminPassword = sca.nextLine();
if (newAdminPassword.equals(againNewAdminPassword)){
break;
}
System.out.println("+ 前后密码不一致");
}
// 判断新密码长度, 小于 10
if (newAdminPassword.length() <= 10){
System.out.println("+ 更新中...");
// 将用户的新密码存储至临时对象中
tempAdmin.setAdminPassword(newAdminPassword);
// 调用数据库更新密码
if (new AdminDaoImpl().updateAdminPassword(admin)){
// 将临时对象中的新密码赋值给用户对象
admin.setAdminPassword(tempAdmin.getAdminPassword());
System.out.println("+ 密码更新成功!");
} else {
System.out.println("+ 密码更新失败!");
}
break;
}
System.out.println("+ 密码过长!");
}
dis.titleLine("按任意键返回主菜单", true);
sca.nextLine();
return;
} else {
System.out.println("+ 密码错误");
System.out.print("+ [y] 重试: ");
String exitKey = sca.next();
if (!Objects.equals(exitKey, "y") && !Objects.equals(exitKey, "Y")){
return;
}
}
}
}
/**
* 管理员添加商家功能
* 该方法通过控制台输入商家相关信息包括商家ID商家名称商家密码商家地址商家介绍起送费和配送费
* 对输入的信息进行验证后将商家信息添加到系统中
*/
public void adminAddBusiness(){
Business business = new Business();
Display dis = new Display('+', '-', 30);
dis.titleLine("新增商家", true);
// 商家 Id
while(true){
String inputBusinessId;
Scanner sca = new Scanner(System.in);
System.out.print("+ 商家四位 ID: ");
inputBusinessId = sca.nextLine();
// 正则表达式判断是否为四位数字
if (Pattern.matches("^\\d{4}$", inputBusinessId)) {
int businessId = Integer.parseInt(inputBusinessId);
business.setBusinessId(businessId);
break;
} else {
if (!inputBusinessId.matches("\\d+")){
System.out.println("+ 输入包含非数字字符!");
}
System.out.println("+ 商家 ID 位数不正确!");
}
}
// 商家名
while (true){
String inputBusinessName;
int maxDataLength = 10;
System.out.print("+ 商家名 (" + maxDataLength + "个字符): ");
inputBusinessName = dis.getStandString(maxDataLength);
if (inputBusinessName != null){
business.setBusinessName(dis.appendSpaceToString(inputBusinessName, maxDataLength));
break;
}
System.out.println("+ 商家名不合法!");
}
// 商家密码
while (true){
String inputBusinessPassword;
int maxDataLength = 10;
System.out.print("+ 商家密码 (" + maxDataLength + "个字符): ");
inputBusinessPassword = dis.getStandString(maxDataLength);
if (inputBusinessPassword != null){
business.setBusinessPassword(inputBusinessPassword);
break;
}
System.out.println("+ 密码不合法!");
}
// 商家地址
while (true){
String inputBusinessAddress;
int maxDataLength = 20;
System.out.print("+ 商家地址 (" + maxDataLength + "个字符): ");
inputBusinessAddress = dis.getStandString(maxDataLength);
if (inputBusinessAddress != null){
business.setBusinessAddress(inputBusinessAddress);
break;
}
System.out.println("+ 商家地址不合法!");
}
// 商家介绍
while (true){
String inputBusinessExplain;
int maxDataLength = 25;
System.out.print("+ 商家介绍 (" + maxDataLength + "个字符): ");
inputBusinessExplain = dis.getStandString(maxDataLength);
if (inputBusinessExplain != null){
business.setBusinessExplain(inputBusinessExplain);
break;
}
System.out.println("+ 商家介绍不合法!");
}
// 起送费
while (true){
double inputBusinessStartPrice;
Scanner sca = new Scanner(System.in);
System.out.print("+ 起送费: ");
if (!sca.hasNextDouble()){
System.out.println("+ 请输入一个有效数字");
sca.next();
} else {
inputBusinessStartPrice = sca.nextDouble();
if (inputBusinessStartPrice > 0 && inputBusinessStartPrice <= 50){
business.setBusinessStarPrice(inputBusinessStartPrice);
break;
} else {
System.out.println("+ 输入数据范围有误 (0 ~ 50)");
}
}
}
// 配送费
while (true){
double inputBusinessDeliveryPrice;
Scanner sca = new Scanner(System.in);
System.out.print("+ 配送费: ");
if (!sca.hasNextDouble()){
System.out.println("+ 请输入一个有效数字");
sca.next();
} else {
inputBusinessDeliveryPrice = sca.nextDouble();
if (inputBusinessDeliveryPrice > 0 && inputBusinessDeliveryPrice <= 50){
business.setBusinessDeliveryPrice(inputBusinessDeliveryPrice);
break;
} else {
System.out.println("+ 输入数据范围有误 (0 ~ 50)");
}
}
}
System.out.println("+ 数据输入完毕! 正在添加商户...");
if (new BusinessDaoImpl().addNewBusiness(business)){
System.out.println("+ 数据添加成功!");
} else {
System.out.println("+ 数据添加失败!");
}
dis.pressEnterToContinue();
}
/**
* 打印业务信息
* 从ResultSet中提取业务相关信息并以格式化的方式打印出来
* 每条业务信息包括业务ID业务名称密码业务地址业务说明星级价格和配送价格
* 业务ID使用四位数字格式化输出
*
* @param rs ResultSet对象包含业务信息的数据
* @return 打印的业务信息条数
*/
public int printInputBusinessInfo(ResultSet rs) {
// 计数器 用户记录输出了多少条信息
int i = 0;
try {
while (rs.next()){
StringBuilder str = new StringBuilder();
str.append("| ");
String formattedNumber = String.format("%04d", rs.getInt("businessId"));
str.append(formattedNumber);
str.append("\t| ");
str.append(rs.getString("businessName"));
str.append("\t| ");
str.append(rs.getString("password"));
str.append("\t| ");
str.append(rs.getString("businessAddress"));
str.append("\t| ");
str.append(rs.getString("businessExplain"));
str.append("\t| ");
str.append(rs.getDouble("starPrice"));
str.append("\t| ");
str.append(rs.getDouble("deliveryPrice"));
str.append("\t|");
System.out.println(str);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
/**
* 打印管理员信息
* 从ResultSet中提取管理员的ID名称和密码并以格式化的形式打印出来
*
* @param rs ResultSet对象包含管理员信息的数据
* @return 打印的管理员数量
*/
public int printAdminInfo(ResultSet rs) {
int i = 0;
try {
while (rs.next()){
StringBuilder str = new StringBuilder();
str.append("| ");
str.append(rs.getInt("adminId"));
str.append("\t| ");
str.append(rs.getString("adminName"));
str.append("\t| ");
str.append(rs.getString("adminPassword"));
str.append("\t|");
String finalString = str.toString();
System.out.println(finalString);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
/**
* 打印所有管理员的信息
* 此方法首先打印一个标题行然后遍历所有管理员信息并打印出来最后显示管理员总数
* 使用了StringBuilder来构建输出字符串以及ResultSet来处理从数据库获取的管理员数据
* 如果在获取或打印数据的过程中发生异常将打印异常堆栈跟踪
*/
public void printAllAdminInfo(){
dis.titleLine("管理员信息", true);
System.out.println("| 管理员ID\t| 管理员名\t| 管理员密码\t|");
try {
// 打印数据
ResultSet rs = new AdminDaoImpl().getAllAdmin();
int num;
num = this.printAdminInfo(rs);
System.out.println("+ 共计 [" + num + "] 条目");
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 打印管理员信息并要求用户确认
* 该方法用于以格式化的方式显示管理员的详细信息包括ID名称和密码
* 在信息显示后要求用户进行确认通过扫描键盘输入来实现
*
* @param admin 管理员对象包含要打印的信息
*/
public void printAdminInfo(Admin admin){
dis.titleLine("管理员 [" + admin.getAdminName() + "]" + " 信息", true);
System.out.println("+ 管理员 ID: " + admin.getAdminId());
System.out.println("+ 管理员名 : " + admin.getAdminName());
System.out.println("+ 管理员密码: " + admin.getAdminPassword());
dis.showLine(true);
Scanner sca = new Scanner(System.in);
sca.nextLine();
}
/**
* 打印所有商家信息
* 此方法用于查询并展示系统中的所有商家信息包括商家的基本信息
* 使用ResultSet遍历查询结果并通过printInputBusinessInfo方法逐条打印商家信息
* 最后打印集合中商家的数量
*/
public void printAllBusinessInfo(){
int num;
dis.titleLine("商家信息", true);
dis.printInfoTitle();
try {
ResultSet rs = new BusinessDaoImpl().printAllBusiness();
num = this.printInputBusinessInfo(rs);
System.out.println("+ 合集商家数目 [" + num + "]");
} catch (Exception e){
e.printStackTrace();
}
}
// 搜索商家
// TODO 代码逻辑需要调整
// TODO 可选择的搜索条目不完善
public void searchBusiness(){
Scanner sca = new Scanner(System.in);
int key;
// 用于接收执行完毕后返回的数据
ResultSet rs;
while ( true ) {
dis.titleLine("搜索商家", true);
dis.showItem("[0] 按商家名查询", true);
dis.showLine(true);
key = dis.getKeyNumber();
switch (key){
case 0:
dis.titleLine("按商家名查询", true);
System.out.print("+ 输入需要查询的商家名: ");
String businessName = sca.next();
try {
System.out.println("+ 查询中...");
rs = new AdminDaoImpl().fuzzyQueryExampleForName(businessName);
// 判断是否为空
if (rs == null){
dis.titleLine("Error", true);
System.out.println("+ 未查询到有关数据!");
return;
}
dis.printInfoTitle();
int num;
num = this.printInputBusinessInfo(rs);
System.out.println("+ 共查询到 " + num + "条数据");
} catch (Exception e){
e.printStackTrace();
}
return;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
}
/**
* 删除商家功能的实现
* 通过用户输入的商家ID或名称从数据库中删除对应的商家信息
* 首先尝试将用户输入解析为整数如果是整数则认为是商家ID并进行删除
* 如果解析失败则认为用户输入的是商家名称并通过名称进行删除
*/
public void deleteBusiness(){
Scanner sca = new Scanner(System.in);
dis.titleLine("删除商家", true);
System.out.print("+ 输入需要删除的商家的 Id 或名字: ");
String uin = sca.nextLine();
try{
int uinToNumber = Integer.parseInt(uin);
System.out.println("+ 查询并删除 Id 为: " + uin + " 的商家...");
new BusinessDaoImpl().deleteId(uinToNumber);
} catch (NumberFormatException e){
System.out.println("+ 查询并删除名为: " + uin + " 的商家...");
new BusinessDaoImpl().deleteName(uin);
}
}
/**
* 打印所有食品的信息
* 该方法用于管理员界面展示数据库中所有食品的详细信息
* 通过查询数据库获取所有食品信息并逐条打印这些信息
*/
public void printAdminAllFoodInfo(){
int num = 0;
dis.titleLine("所有食品列表", true);
try {
System.out.println("+ 查询中...");
ResultSet rs = new BusinessDaoImpl().getAllFoodInfo();
// 判断是否为空
if (rs == null){
dis.titleLine("Error", true);
System.out.println("+ 未查询到有关数据!");
return;
}
while ( rs.next() ){
StringBuilder str = new StringBuilder();
str.append("| ");
str.append(rs.getString("foodId"));
str.append("\t| ");
str.append(rs.getString("foodName"));
str.append("\t| ");
str.append(rs.getString("foodExplain"));
str.append("\t| ");
str.append(rs.getDouble("foodPrice"));
str.append("\t| ");
str.append(rs.getInt("businessId"));
str.append("\t|");
String finalString = str.toString();
System.out.println(finalString);
num++;
}
System.out.println("+ 共查询到 " + num + " 条数据");
} catch (Exception e){
e.printStackTrace();
}
}
}

616
src/View/BusinessView.java Normal file
View File

@ -0,0 +1,616 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package View;
import dao.BusinessDaoImpl;
import po.Business;
import po.Food;
import java.sql.ResultSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Pattern;
public class BusinessView {
Display dis = new Display('+', '-', 30);
/**
* 商户登录方法
* 通过 Scanner 从标准输入获取商户的用户名或ID和密码尝试进行登录
* 如果商户输入的用户名或ID和密码匹配成功则返回对应的商户对象否则允许商户尝试多次登录直到尝试次数用尽
*
* @return 成功登录时返回商户对象否则返回 null
*/
public Business login () {
Scanner sca = new Scanner(System.in);
// 当前错误次数
int mistake = 0;
// 用户可以的最大错误次数
int maxMistake = 3;
int loginCode;
Business business = null;
while ( mistake < maxMistake ) {
dis.titleLine("登录 [饿了么] 商家后台", true);
// 错误次数大于 1 输出文字提醒用户
if ( mistake != 0 ) {
System.out.println("+ 密码输入错误 " + mistake + " 次 剩余可尝试次数 " + (maxMistake - mistake) + "");
}
String inputBusinessNameOrId;
int inputBusinessId = - 1;
System.out.print("+ 账户&Id: ");
inputBusinessNameOrId = sca.nextLine();
try {
inputBusinessId = Integer.parseInt(inputBusinessNameOrId);
loginCode = 0;
} catch ( NumberFormatException e ) {
loginCode = 1;
}
String inputBusinessPassword;
System.out.print("+ 密码: ");
inputBusinessPassword = sca.nextLine();
System.out.println("+ 登录系统中...");
if ( loginCode == 0 ) {
business = new BusinessDaoImpl().getBusinessByIdByPass(inputBusinessId, inputBusinessPassword);
}
if ( loginCode == 1 ) {
business = new BusinessDaoImpl().getBusinessByNameByPass(inputBusinessNameOrId, inputBusinessPassword);
}
if ( business != null ) {
return business;
} else {
mistake++;
}
}
return null;
}
/**
* 打印商家信息
* 该方法详细打印了商家的各种信息包括ID名称密码介绍地址起送费和配送费
* 旨在为商家管理提供可视化的信息展示方便用户查看和管理商家详情
*
* @param business 商家对象包含需要打印的所有商家信息
*/
public void printBusinessInfo (Business business) {
String businessName = dis.deleteSpaceToString(business.getBusinessName());
String businessPassword = dis.deleteSpaceToString(business.getBusinessPassword());
String businessExplain = dis.deleteSpaceToString(business.getBusinessExplain());
String businessAddress = dis.deleteSpaceToString(business.getBusinessAddress());
dis.titleLine("商家 [" + businessName + "]" + " 信息", true);
String formattedNumber = String.format("%04d", business.getBusinessId());
System.out.println("+ 商家 ID: " + formattedNumber);
System.out.println("+ 商家名 :" + businessName);
System.out.println("+ 商家密码:" + businessPassword);
System.out.println("+ 商家介绍:" + businessExplain);
System.out.println("+ 商家地址:" + businessAddress);
System.out.println("+ 起送费: " + business.getBusinessStarPrice());
System.out.println("+ 配送费: " + business.getBusinessDeliveryPrice());
dis.showLine(true);
dis.pressEnterToContinue();
}
/**
* 打印食品信息列表
* 该方法从 ResultSet 对象中获取食品信息并逐行打印出来
* 旨在提供可视化的展示食品信息列表方便用户查看和管理食品信息
*
* @param rs ResultSet 对象包含需要打印的所有食品信息
* @return 打印食品信息列表的行数
*/
public int printFoodInfoList (ResultSet rs) {
int num = 0;
try {
while ( rs.next() ) {
StringBuilder str = new StringBuilder();
str.append("| ");
String formattedNumber = String.format("%04d", rs.getInt("foodId"));
str.append(formattedNumber);
str.append("\t| ");
str.append(rs.getString("foodName"));
str.append("\t| ");
str.append(rs.getString("foodExplain"));
str.append("\t| ");
str.append(rs.getDouble("foodPrice"));
str.append("\t|");
String finalStr = str.toString();
System.out.println(finalStr);
num++;
}
return num;
} catch ( Exception e ) {
e.printStackTrace();
}
return num;
}
/**
* 打印食品信息列表的标题
* 该方法打印了食品信息列表的标题包括ID食品名食品介绍价格等字段
* 旨在提供可视化的展示食品信息列表的标题方便用户查看和管理食品信息
*/
public void printFoodInfoListTitle () {
System.out.println("| ID\t| 食品名\t\t\t| 食品介绍\t\t\t\t\t| 价格\t|");
}
/**
* 打印所有商家食品信息
* 该方法从 ResultSet 对象中获取商家食品信息并逐行打印出来
* 旨在提供可视化的展示所有商家食品信息方便用户查看和管理食品信息
*
* @param business 商家对象包含需要打印的所有商家信息
*/
public void printAllBusinessFoodInfo (Business business) {
dis.titleLine("商家 [" + dis.deleteSpaceToString(business.getBusinessName()) + "] 的商品", true);
try {
System.out.println("+ 查询中...");
ResultSet rs = new BusinessDaoImpl().getBusinessFoodInfo(business);
// 判断是否为空
if ( rs == null ) {
dis.titleLine("Error", true);
System.out.println("+ 未查询到有关数据!");
return;
}
this.printFoodInfoListTitle();
int num = this.printFoodInfoList(rs);
System.out.println("+ 共查询到 " + num + " 条数据");
} catch ( Exception e ) {
e.printStackTrace();
}
dis.showLine(true);
dis.pressEnterToContinue();
}
/**
* 更新商家信息
* 该方法允许用户更新商家信息包括商家名商家介绍商家地址起送费和配送费等字段
* 旨在提供可视化的更新商家信息方便用户管理商家信息
*
* @param business 商家对象包含需要更新的商家信息
*/
public void updateBusinessInfo (Business business) {
Business newBusiness = new Business(business);
int key;
boolean exitStatus = false;
while ( true ) {
dis.titleLine("更改商家信息", true);
System.out.println("[0] 更改商家名");
System.out.println("[1] 更改商家介绍");
System.out.println("[2] 更改商家地址");
System.out.println("[3] 更改商家起送费");
System.out.println("[4] 更改商家配送费");
System.out.println("[5] 退出更改");
dis.showLine(true);
key = dis.getKeyNumber();
switch ( key ) {
case 0:
while ( true ) {
String newBusinessName;
int maxDataLength = 10;
dis.titleLine("更改商家名", true);
System.out.print("+ 输入新商家名 (" + maxDataLength + "个字符): ");
newBusinessName = dis.getStandString(maxDataLength);
if (newBusinessName != null){
newBusiness.setBusinessName(newBusinessName);
break;
}
System.out.println("+ 商家名称不合法");
}
break;
case 5:
return;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
System.out.println("+ 数据输入完毕, 是否需要选择其它更改的项目");
System.out.println("+ [y] - 确认更改更新商家数据");
System.out.println("+ [n] - 继续输入需要更改的数据");
System.out.println("+ [e] - 退出, 放弃需要更改的数据");
System.out.print("+ 请输入需要的操作: ");
while ( true ) {
Scanner sca = new Scanner(System.in);
String str_key = sca.nextLine();
if ( str_key.equals("y") || str_key.equals("Y") ) {
System.out.println("+ 更新数据中...");
if ( new BusinessDaoImpl().updateBusinessInfo(newBusiness) ) {
System.out.println("+ 更新完毕...");
} else {
System.out.println("+ 更新失败...");
}
exitStatus = true;
break;
}
if ( str_key.equals("n") || str_key.equals("N") ) { break; }
if ( str_key.equals("e") || str_key.equals("E") ) {
System.out.println("+ 退出更改");
exitStatus = true;
break;
}
System.out.println("+ 输入不合法!");
}
if ( exitStatus ) { break; }
}
dis.showLine(true);
dis.pressEnterToContinue();
}
/**
* 更新商家密码
* 该方法提供了一个交互式的界面用于商家验证当前密码并设置新密码
* 它确保了新密码的正确性和安全性长度至少为10个字符
*
* @param business 管理员对象包含当前管理员信息
*/
public void updatePassword (Business business) {
// 创建临时商户对象接收更改密码期间的用户输入
Business tempBusiness = new Business(business);
dis.titleLine("更改密码", true);
while (true){
// 引导用户输入原来的密码
Scanner sca = new Scanner(System.in);
String afterBusinessPassword;
System.out.print("+ 输入原密码: ");
afterBusinessPassword = sca.nextLine();
// 判断新旧密码是否相等
if (afterBusinessPassword.equals(tempBusiness.getBusinessPassword())){
System.out.println("+ 密码正确");
while (true){
String newBusinessPassword;
// 两次输入密码确保用户不会误输入
while (true){
String againNewBusinessPassword;
System.out.print("+ 输入新密码 (10个字符): ");
newBusinessPassword = sca.nextLine();
System.out.print("+ 再次新密码 (10个字符): ");
againNewBusinessPassword = sca.nextLine();
if (newBusinessPassword.equals(againNewBusinessPassword)){
break;
}
System.out.println("+ 前后密码不一致");
}
// 判断新密码长度, 小于 10
if (newBusinessPassword.length() <= 10){
System.out.println("+ 更新中...");
// 将用户的新密码存储至临时对象中
tempBusiness.setBusinessPassword(newBusinessPassword);
// 调用数据库更新密码
if (new BusinessDaoImpl().updateBusinessPassword(tempBusiness)){
// 将临时对象中的新密码赋值给用户对象
business.setBusinessPassword(tempBusiness.getBusinessPassword());
System.out.println("+ 密码更新成功!");
} else {
System.out.println("+ 密码更新失败!");
}
break;
}
System.out.println("+ 密码过长!");
}
dis.titleLine("按任意键返回主菜单", true);
sca.nextLine();
return;
} else {
System.out.println("+ 密码错误");
System.out.print("+ [y] 重试: ");
String exitKey = sca.next();
if (!Objects.equals(exitKey, "y") && !Objects.equals(exitKey, "Y")){
return;
}
}
}
}
/**
* 添加新的食品
* 该方法提供了一个交互式的界面用于添加新的食品
* 它确保了食品名称的正确性和安全性长度至少为10个字符
*
* @param business 管理员对象包含当前管理员信息
*/
public void addBusinessNewFood (Business business) {
Food food = new Food();
Display dis = new Display('+', '-', 50);
dis.titleLine("增加商家食品", true);
while ( true ) {
String foodId;
Scanner sca = new Scanner(System.in);
System.out.print("+ 输入食品编号 (10个字符): ");
foodId = sca.nextLine();
if ( Pattern.matches("^\\d{4}$", foodId) ) {
int foodIdForInt = Integer.parseInt(foodId);
food.setFoodId(foodIdForInt);
break;
} else {
if ( ! foodId.matches("\\d+") ) {
System.out.println("+ 输入包含非数字字符!");
} else {
System.out.println("+ ID 位数不正确!");
}
}
}
while ( true ) {
String foodName;
int max_length = 10;
System.out.print("+ 输入食品名 (" + max_length + "个字符): ");
foodName = dis.getStandString(max_length);
if (foodName != null){
food.setFoodName(foodName);
break;
}
System.out.println("+ 食品名不合法!");
}
while ( true ) {
String foodExplain;
int max_length = 25;
System.out.print("+ 输入食品介绍 (" + max_length + "个字符): ");
foodExplain = dis.getStandString(max_length);
if (foodExplain != null){
food.setFoodExplain(foodExplain);
break;
}
System.out.println("+ 食品介绍不合法!");
}
while ( true ) {
double foodPrice;
Scanner sca = new Scanner(System.in);
System.out.print("+ 输入食品价格: ");
if ( ! sca.hasNextDouble() ) {
System.out.println("+ 输入不合法");
sca.next();
} else {
foodPrice = sca.nextDouble();
if ( foodPrice > 0 && foodPrice <= 9999 ) {
food.setFoodPrice(foodPrice);
break;
} else {
System.out.println("+ 数据范围不符 (0 ~ 9999)");
}
}
}
// 同步 ID
food.setBusinessId(business.getBusinessId());
while ( true ) {
dis.showLine(true);
System.out.println("+ [y] 确认添加食品");
System.out.println("+ [n] 取消添加食品 ");
Scanner sca = new Scanner(System.in);
String exitKey = sca.next();
if ( exitKey.equals("y") || exitKey.equals("Y") ) {
if ( new BusinessDaoImpl().addNewFood(food) ) {
System.out.println("+ 添加成功!");
} else {
System.out.println("+ 添加失败!");
}
return;
} else if ( exitKey.equals("n") || exitKey.equals("N") ) {
System.out.println("+ 退出添加");
return;
}
}
}
/**
* 更新食品信息
* 该方法提供了一种交互式的界面用于更新食品信息
* 它确保了食品名称的正确性和安全性长度至少为10个字符
*
* @param business 管理员对象包含当前管理员信息
*/
public void updateBusinessFoodInfo (Business business) {
Display dis = new Display('+', '-', 30);
Food updateFood;
dis.titleLine("修改食品信息", true);
System.out.println("+ 用户 [" + business.getBusinessName() + "] 的食品有如下表");
ResultSet rs = new BusinessDaoImpl().getBusinessFoodInfo(business);
this.printFoodInfoListTitle();
this.printFoodInfoList(rs);
dis.showLine(true);
int updateFoodId;
while ( true ){
Scanner sca = new Scanner(System.in);
System.out.print("+ 输入需要修改的食品项目 ID: ");
while ( ! sca.hasNextInt() ) {
System.out.println("+ 仅可输入整数 ID");
sca.next();
System.out.print("+ 输入需要修改的食品项目 ID: ");
}
updateFoodId = sca.nextInt();
updateFood = new BusinessDaoImpl().getFoodById(updateFoodId, business.getBusinessId());
if ( updateFood != null ){
System.out.println("+ 检索成功!");
break;
}
System.out.println("+ 未能查询到指定的商品");
}
int key;
while ( true ) {
dis.titleLine("选择需要修改的项目", true);
dis.showItem("[0] 商品名", true);
dis.showItem("[1] 商品介绍", true);
dis.showItem("[2] 商品价格", true);
dis.showItem("[3] 更新食品信息", true);
dis.showItem("[4] 返回上级", true);
dis.showLine(true);
key = dis.getKeyNumber();
switch ( key ) {
case 0:
while ( true ) {
String foodName;
int maxDataLength = 10;
System.out.print("+ 输入食品名 (" + maxDataLength + "个字符): ");
foodName = dis.getStandString(maxDataLength);
if (foodName != null){
updateFood.setFoodName(foodName);
break;
}
System.out.println("+ 食品名不合法");
}
break;
case 1:
while ( true ) {
String foodExplain;
int maxDataLength = 10;
System.out.print("+ 输入食品介绍 (" + maxDataLength + "个字符): ");
foodExplain = dis.getStandString(maxDataLength);
if (foodExplain != null){
updateFood.setFoodExplain(foodExplain);
break;
}
System.out.println("+ 食品介绍不合法");
}
break;
case 2:
while ( true ) {
double foodPrice;
Scanner case2_sca = new Scanner(System.in);
System.out.print("+ 输入食品价格: ");
if ( ! case2_sca.hasNextDouble() ) {
System.out.println("+ 输入错误,请输入一个有效的数字作为食品价格!");
case2_sca.next();
} else {
foodPrice = case2_sca.nextDouble();
if ( foodPrice > 0 && foodPrice <= 9999 ) {
updateFood.setFoodPrice(foodPrice);
break;
} else {
System.out.println("+ 数据范围有误! 数据需要 (0 ~ 9999)");
}
}
}
case 3:
while (true){
dis.titleLine("确认更新食品信息", true);
System.out.println("+ [y] 确认更新食品信息");
System.out.print("+ [n] 取消更新食品信息: ");
Scanner case3_sca = new Scanner(System.in);
String case3_Key = case3_sca.next();
if (case3_Key.equals("y") || case3_Key.equals("Y")) {
updateFood.setFoodId(updateFoodId);
updateFood.setBusinessId(business.getBusinessId());
if (new BusinessDaoImpl().updateFoodInfo(updateFood, business)){
System.out.println("+ 更新成功!");
break;
}
System.out.println("+ 更新失败");
} else if (case3_Key.equals("n") || case3_Key.equals("N")) { break; }
}
break;
case 4:
if (dis.MessageYesOrNo("提示", "确定返回上级菜单?")) {
return;
}
break;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
}
/**
* 删除食品信息
* 通过输入食品的ID或名称尝试删除相应的食品记录
* 首先尝试将输入解析为ID如果失败则视为食品名称
*
* @param business 业务对象用于执行删除操作
*/
public void deleteFood(Business business){
Scanner sca = new Scanner(System.in);
dis.titleLine("删除食品", true);
System.out.print("+ 输入需要删除的食品的 ID 或名字: ");
String uin = sca.nextLine();
try{
int uinToNumber = Integer.parseInt(uin);
System.out.println("+ 查询并删除 ID 为: " + uin + " 的食品...");
if (new BusinessDaoImpl().deleteFoodId(uinToNumber, business)){
System.out.println("+ ID 删除成功");
return;
}
System.out.println("+ ID 删除失败");
} catch (NumberFormatException e){
System.out.println("+ 查询并删除名为: " + uin + " 的食品...");
if (new BusinessDaoImpl().deleteFoodName(dis.appendSpaceToString(uin, 10), business)){
System.out.println("+ NAME 删除成功");
return;
}
System.out.println("+ NAME 删除失败");
}
}
}

212
src/View/Display.java Normal file
View File

@ -0,0 +1,212 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package View;
import java.util.Scanner;
public class Display {
// 成员变量
private char displayNode; // 字符
private char displayLine; // 分割 字符
private Integer displayWidth; // 显示宽度
Scanner sca = new Scanner(System.in);
// 构造函数
public Display (char node, char line, Integer width){
displayNode = node;
displayLine = line;
displayWidth = width;
}
/**
* 在控制台上以标题形式输出给定的字符串
* 根据控制台宽度自动调整标题的左右空白宽度使其居中显示
*
* @param title 要输出的标题字符串
* @param newLine 是否在输出后换行如果为true则在输出标题后换行如果为false则不换行
*/
public void titleLine (String title, boolean newLine){
StringBuilder str = new StringBuilder();
int space = (displayWidth - title.length() - 2) / 2;
str.append(displayNode);
str.append(String.valueOf(displayLine).repeat(Math.max(0, space)));
str.append(title);
str.append(String.valueOf(displayLine).repeat(Math.max(0, space)));
str.append(displayNode);
String finalStr = str.toString();
System.out.print(finalStr);
if (newLine){ System.out.println(); }
}
/**
* 在控制台输出一个项目并自动调整项目左右空白宽度使其居中显示
*
* @param item 要输出的项目字符串
* @param newLine 是否在输出后换行如果为true则在输出项目后换行如果为false则不换行
*/
public void showItem(String item, boolean newLine){
StringBuilder str = new StringBuilder();
str.append(displayNode).append(" ");
str.append(item);
String finalStr = str.toString();
System.out.print(finalStr);
if (newLine){ System.out.println(); }
}
/**
* 在控制台输出一条分割线
*
* @param newLine 是否在输出后换行如果为true则在输出分割线后换行如果为false则不换行
*/
public void showLine(boolean newLine){
StringBuilder str = new StringBuilder();
str.append(displayNode);
str.append(String.valueOf(displayLine).repeat(Math.max(0, displayWidth - 2)));
str.append(displayNode);
String finalStr = str.toString();
System.out.print(finalStr);
if (newLine){ System.out.println(); }
}
/**
* 在控制台输出一条消息并询问用户是否确认或取消
*
* @param title 消息的标题
* @param data 消息的内容
* @return 如果用户确认则返回true如果用户取消则返回false
*/
public boolean MessageYesOrNo(String title, String data){
this.titleLine(title, true);
System.out.println("+ " + data);
System.out.print("+ (y/n) 确认&取消 ");
String key = sca.next();
return key.equals("y") || key.equals("Y");
}
/**
* 从用户输入中获取一个整数
* 该方法不断提示用户输入一个整数直到用户输入正确的整数为止
*
* @return 用户输入的整数值
*/
public int getKeyNumber(){
int userInput;
System.out.print("+ 请输入操作数: ");
while(!sca.hasNextInt()){
this.titleLine("ERROR", true);
System.out.println("+ 仅可输入整数的操作数");
sca.next();
System.out.print("+ 请输入操作数: ");
}
userInput = sca.nextInt();
return userInput;
}
/**
* 在字符串后面添加空格直到字符串的总长度达到指定的最大长度
* 如果原始字符串的长度已经等于或超过最大长度则原样返回该字符串
*
* @param data 原始字符串
* @param max_length 指定的最大长度
* @return 添加空格后的字符串
*/
public String appendSpaceToString(String data, int max_length){
StringBuilder str = new StringBuilder();
int dataLength = data.length();
if (dataLength < max_length){
str.append(data);
int space = max_length - dataLength;
str.append(" ".repeat(space));
return str.toString();
} else {
return data;
}
}
/**
* 删除字符串末尾的空格
* 如果字符串为空或空字符串则返回原字符串
*
* @param data 原始字符串
* @return 删除末尾空格后的字符串
*/
public String deleteSpaceToString(String data){
// 判断是否为空
if (data == null || data.isEmpty()){
return data;
}
int length = data.length();
while (length > 0 && data.charAt(length - 1) == ' '){
length--;
}
return data.substring(0, length);
}
/**
* 打印信息标题
* 该方法打印一个带有标题的表格用于显示商家信息
*/
public void printInfoTitle(){
System.out.println("| 商家ID\t| 商家名\t\t\t| 商家密码\t\t| 商家地址\t\t\t\t| 商家介绍\t\t\t\t\t| 起送费\t| 配送费\t|");
}
/**
* 获取标准字符串
* 该方法从用户输入中获取一个字符串并删除末尾的空格
* 如果输入的字符串长度超过指定的最大长度则返回null
*
* @param max_length 指定的最大长度
* @return 标准字符串如果输入的字符串长度超过指定的最大长度则返回null
*/
public String getStandString(int max_length){
StringBuilder str = new StringBuilder();
Scanner sca = new Scanner(System.in);
String input = sca.nextLine();
int inputLength = input.length();
// 追加空格
if (inputLength < max_length){
str.append(input);
int space = max_length - inputLength;
str.append(" ".repeat(space));
return str.toString();
}
if (inputLength == max_length){
return input;
}
return null;
}
/**
* 提示用户按回车键继续
*/
public void pressEnterToContinue(){
System.out.println("+ 按回车键继续...");
sca.nextLine();
}
}

18
src/dao/AdminDao.java Normal file
View File

@ -0,0 +1,18 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package dao;
import po.Admin;
import java.sql.ResultSet;
public interface AdminDao {
Admin getAdminByNameByPass(String adminName, String password);
Admin getAdminByIdByPass(int adminId, String password);
boolean updateAdminPassword(Admin admin);
ResultSet fuzzyQueryExampleForName(String name);
ResultSet getAllAdmin();
}

184
src/dao/AdminDaoImpl.java Normal file
View File

@ -0,0 +1,184 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package dao;
import jdbc.JDBC;
import po.Admin;
import java.sql.*;
public class AdminDaoImpl implements AdminDao{
/**
* 通过用户名和密码获取管理员信息
* 此方法尝试通过提供的用户名和密码从数据库中检索管理员账户信息
* 如果找到匹配的管理员它将返回一个包含管理员详细信息的Admin对象
* 如果没有找到匹配或发生数据库错误则返回null
*
* @param adminName 管理员用户名
* @param password 管理员密码
* @return 匹配的管理员对象如果没有找到或发生错误则为null
*/
@Override
public Admin getAdminByNameByPass(String adminName, String password) {
Admin admin = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM admin WHERE adminName = '" + adminName + "' AND adminPassword = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
admin = new Admin();
admin.setAdminId(rs.getInt("adminId"));
admin.setAdminName(rs.getString("adminName"));
admin.setAdminPassword(rs.getString("adminPassword"));
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return admin;
}
/**
* 通过管理员ID和密码获取管理员信息
* 此方法尝试通过提供的管理员ID和密码从数据库中检索管理员账户信息
* 如果找到匹配的管理员它将返回一个包含管理员详细信息的Admin对象
* 如果没有找到匹配或发生数据库错误则返回null
*
* @param adminId 管理员ID
* @param password 管理员密码
* @return 匹配的管理员对象如果没有找到或发生错误则为null
*/
@Override
public Admin getAdminByIdByPass(int adminId, String password) {
Admin admin = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM admin WHERE adminId = '" + adminId + "' AND adminPassword = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
admin = new Admin();
admin.setAdminId(rs.getInt("adminId"));
admin.setAdminName(rs.getString("adminName"));
admin.setAdminPassword(rs.getString("adminPassword"));
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return admin;
}
/**
* 更新管理员密码
* 此方法尝试更新管理员密码
* 如果更新成功则返回true
* 如果更新失败或发生数据库错误则返回false
*
* @param admin 管理员对象包含要更新的管理员信息
* @return 更新成功返回true否则返回false
*/
@Override
public boolean updateAdminPassword(Admin admin) {
try {
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
System.out.println("+ 连接到数据库");
String sql = "UPDATE admin SET adminPassword = ? WHERE adminId = ?";
PreparedStatement pst = conn.prepareStatement(sql);
// 需要更新的用户的Id
int adminIdToUpdate = admin.getAdminId();
// 需要更新成的密码
String newAdminPassword = admin.getAdminPassword();
pst.setString(1, newAdminPassword);
pst.setInt(2, adminIdToUpdate);
int rowsAffected = pst.executeUpdate();
stmt.close();
conn.close();
pst.close();
return rowsAffected > 0;
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return false;
}
/**
* 通过模糊查询获取所有管理员信息
* 此方法尝试通过模糊查询从数据库中检索所有管理员信息
* 如果找到匹配的管理员它将返回一个包含管理员详细信息的ResultSet对象
* 如果没有找到匹配或发生数据库错误则返回null
*
* @param name 管理员名称
* @return 匹配的管理员对象如果没有找到或发生错误则为null
*/
@Override
public ResultSet fuzzyQueryExampleForName(String name) {
try{
Connection conn = JDBC.getConnection();
String sql = "SELECT * FROM business WHERE businessName LIKE ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name + "%");
return pstmt.executeQuery();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 获取所有管理员信息
* 此方法尝试从数据库中检索所有管理员信息
* 如果找到匹配的管理员它将返回一个包含管理员详细信息的ResultSet对象
* 如果没有找到匹配或发生数据库错误则返回null
*
* @return 所有管理员对象如果没有找到或发生错误则为null
*/
@Override
public ResultSet getAllAdmin() {
try{
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM admin";
return stmt.executeQuery(sql);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}

29
src/dao/BusinessDao.java Normal file
View File

@ -0,0 +1,29 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package dao;
import po.Business;
import po.Food;
import java.sql.ResultSet;
public interface BusinessDao {
boolean addNewBusiness(Business business);
ResultSet printAllBusiness();
Business getBusinessByNameByPass(String name, String password);
Business getBusinessByIdByPass(Integer id, String password);
void deleteId(int id);
void deleteName(String Name);
boolean updateBusinessInfo(Business business);
boolean updateBusinessPassword(Business business);
boolean addNewFood(Food food);
ResultSet getAllFoodInfo();
boolean updateFoodInfo(Food food, Business business);
Food getFoodById(int foodId, int businessId);
boolean deleteFoodId(int foodId, Business business);
boolean deleteFoodName(String foodName, Business business);
ResultSet getBusinessFoodInfo(Business business);
}

View File

@ -0,0 +1,514 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package dao;
import View.Display;
import jdbc.JDBC;
import po.Business;
import po.Food;
import java.sql.*;
public class BusinessDaoImpl implements BusinessDao{
/**
* 添加新的商家信息到数据库
*
* @param business 待添加的商家对象包含商家的所有相关信息
* @return 如果成功添加商家信息则返回true否则返回false
*/
@Override
public boolean addNewBusiness(Business business){
try {
Connection conn = JDBC.getConnection();
String sql = "INSERT INTO business (businessId, password, businessName, businessAddress, businessExplain, starPrice, deliveryPrice) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, business.getBusinessId());
pstmt.setString(2, business.getBusinessPassword());
pstmt.setString(3, business.getBusinessName());
pstmt.setString(4, business.getBusinessAddress());
pstmt.setString(5, business.getBusinessExplain());
pstmt.setDouble(6, business.getBusinessStarPrice());
pstmt.setDouble(7, business.getBusinessDeliveryPrice());
pstmt.executeUpdate();
pstmt.close();
conn.close();
return true;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 查询所有业务信息并返回结果集
* 本方法通过建立数据库连接创建Statement对象执行SQL查询语句
* 以获取所有业务信息的结果集如果在操作过程中发生异常将打印异常堆栈跟踪
*
* @return ResultSet 包含所有业务信息的结果集如果发生异常返回null
*/
@Override
public ResultSet printAllBusiness() {
try{
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM business";
return stmt.executeQuery(sql);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 根据名称和密码获取商家信息
* 通过数据库查询匹配名称和密码的商家并返回其详细信息
*
* @param name 商家名称
* @param password 商家密码
* @return 匹配成功返回Business对象否则返回null
*/
@Override
public Business getBusinessByNameByPass(String name, String password) {
Business business = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM business WHERE businessName = '" + name + "' AND password = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
business = new Business();
business.setBusinessId(rs.getInt("businessId"));
business.setBusinessName(rs.getString("businessName"));
business.setBusinessPassword(rs.getString("password"));
business.setBusinessExplain(rs.getString("businessExplain"));
business.setBusinessAddress(rs.getString("businessAddress"));
business.setBusinessStarPrice(rs.getDouble("starPrice"));
business.setBusinessDeliveryPrice(rs.getDouble("deliveryPrice"));
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return business;
}
/**
* 根据ID和密码获取商家信息
* 通过数据库查询匹配ID和密码的商家并返回其详细信息
*
* @param id 商家ID
* @param password 商家密码
* @return 匹配成功返回Business对象否则返回null
*/
@Override
public Business getBusinessByIdByPass(Integer id, String password) {
Business business = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM business WHERE businessId = '" + id + "' AND password = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
business = new Business();
business.setBusinessId(rs.getInt("businessId"));
business.setBusinessName(rs.getString("businessName"));
business.setBusinessPassword(rs.getString("password"));
business.setBusinessExplain(rs.getString("businessExplain"));
business.setBusinessAddress(rs.getString("businessAddress"));
business.setBusinessStarPrice(rs.getDouble("starPrice"));
business.setBusinessDeliveryPrice(rs.getDouble("deliveryPrice"));
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return business;
}
/**
* 获取指定商家的所有食品信息
* 通过数据库查询指定商家的所有食品信息并返回结果集
*
* @param business 商家对象
* @return ResultSet 包含指定商家的所有食品信息的结果集如果发生异常返回null
*/
@Override
public ResultSet getBusinessFoodInfo(Business business){
try{
Connection conn = JDBC.getConnection();
String sql = "SELECT * FROM food WHERE businessId = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, business.getBusinessId());
return pstmt.executeQuery();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 根据ID删除商家
* 通过数据库删除指定ID的商家
*
* @param id 商家ID
*/
@Override
public void deleteId(int id) {
try{
Connection conn = JDBC.getConnection();
String sql = "DELETE FROM business WHERE businessId = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, id);
int rowsAffected = prep.executeUpdate();
if (rowsAffected > 0){
System.out.println("+ 成功删除 " + rowsAffected + " 个商家");
} else {
System.out.println("+ 未找到符合条件的商家");
}
prep.close();
conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 根据名称删除商家
* 通过数据库删除指定名称的商家
*
* @param Name 商家名称
*/
@Override
public void deleteName(String Name) {
try{
Connection conn = JDBC.getConnection();
String sql = "DELETE FROM business WHERE businessName = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, Name);
int rowsAffected = prep.executeUpdate();
if (rowsAffected > 0){
System.out.println("+ 成功删除 " + rowsAffected + " 个商家");
} else {
System.out.println("+ 未找到符合条件的商家");
}
prep.close();
conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 更新商家信息
* 通过数据库更新指定ID的商家信息
*
* @param business 商家对象
* @return true 更新成功false 更新失败
*/
@Override
public boolean updateBusinessInfo (Business business) {
try {
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "UPDATE business SET businessName = ?, businessAddress = ?, businessExplain = ?, starPrice = ?, deliveryPrice = ? WHERE businessId = ?";
PreparedStatement pst = conn.prepareStatement(sql);
int businessIdToUpdate = business.getBusinessId();
pst.setString(1, business.getBusinessName());
pst.setString(2, business.getBusinessAddress());
pst.setString(3, business.getBusinessExplain());
pst.setDouble(4, business.getBusinessStarPrice());
pst.setDouble(5, business.getBusinessDeliveryPrice());
pst.setInt(6, businessIdToUpdate);
int rowsAffected = pst.executeUpdate();
stmt.close();
conn.close();
pst.close();
return rowsAffected > 0;
} catch ( Exception e ){
e.printStackTrace();
}
return false;
}
/**
* 更新商家密码
* 通过数据库更新指定ID的商家密码
*
* @param business 商家对象
* @return true 更新成功false 更新失败
*/
@Override
public boolean updateBusinessPassword (Business business) {
try {
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
System.out.println("+ 连接到数据库");
String sql = "UPDATE business SET password = ? WHERE businessId = ?";
PreparedStatement pst = conn.prepareStatement(sql);
// 需要更新的用户的Id
int newBusinessIdToUpdate = business.getBusinessId();
// 需要更新成的密码
String newBusinessPassword = business.getBusinessPassword();
pst.setString(1, newBusinessPassword);
pst.setInt(2, newBusinessIdToUpdate);
int rowsAffected = pst.executeUpdate();
stmt.close();
conn.close();
pst.close();
return rowsAffected > 0;
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return false;
}
/**
* 添加新的食品
* 通过数据库添加新的食品
*
* @param food 食品对象
* @return true 添加成功false 添加失败
*/
@Override
public boolean addNewFood (Food food) {
try {
Connection conn = JDBC.getConnection();
String sql = "INSERT INTO food (foodId, foodName, foodExplain, foodPrice, businessId) VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, food.getFoodId());
pstmt.setString(2, food.getFoodName());
pstmt.setString(3, food.getFoodExplain());
pstmt.setDouble(4, food.getFoodPrice());
pstmt.setInt(5, food.getBusinessId());
pstmt.executeUpdate();
pstmt.close();
conn.close();
return true;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 获取所有食品信息
* 通过数据库获取所有食品信息
*
* @return ResultSet 食品信息
*/
@Override
public ResultSet getAllFoodInfo () {
try{
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM food";
return stmt.executeQuery(sql);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 更新食品信息
* 通过数据库更新指定ID的食品信息
*
* @param food 食品对象
* @param business 商家对象
* @return true 更新成功false 更新失败
*/
@Override
public boolean updateFoodInfo (Food food, Business business) {
try {
Connection conn = JDBC.getConnection();
// 3. 准备SQL语句
String sql = "UPDATE food SET foodName = ?, foodExplain = ?, foodPrice = ? WHERE businessId = ? AND foodId = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, food.getFoodName());
pstmt.setString(2, food.getFoodExplain());
pstmt.setDouble(3, food.getFoodPrice());
pstmt.setInt(4, food.getBusinessId());
pstmt.setInt(5, food.getFoodId());
int rowsAffected = pstmt.executeUpdate();
pstmt.close();
conn.close();
return rowsAffected > 0;
} catch ( Exception e ) {
e.printStackTrace();
}
return false;
}
/**
* 根据食品ID和商家ID获取食品信息
* 这个方法通过查询数据库来获取特定ID的食品的详细信息
*
* @param foodId 食品的唯一标识ID
* @param businessId 商家的唯一标识ID用于确定食品属于哪个商家
* @return 返回一个Food对象包含查询到的食品信息如果没有找到匹配的食品则返回null
*/
@Override
public Food getFoodById (int foodId, int businessId) {
Food food = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM food WHERE foodId = '" + foodId + "' AND businessId = '" + businessId + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
food = new Food();
food.setFoodName(rs.getString("foodName"));
food.setFoodExplain(rs.getString("foodExplain"));
food.setFoodPrice(rs.getDouble("foodPrice"));
food.setFoodId(rs.getInt("foodId"));
food.setBusinessId(rs.getInt("businessId"));
}
conn.close();
stmt.close();
rs.close();
return food;
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return food;
}
/**
* 根据食品ID和商家ID删除食品
* 这个方法通过删除数据库中的特定食品记录来删除食品
*
* @param foodId 食品的唯一标识ID
* @param business 商家的唯一标识ID用于确定食品属于哪个商家
* @return 如果删除成功则返回true否则返回false
*/
@Override
public boolean deleteFoodId (int foodId, Business business) {
try{
Connection conn = JDBC.getConnection();
String sql = "DELETE FROM food WHERE businessId = ? AND foodId = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, business.getBusinessId());
prep.setInt(2, foodId);
int rowsAffected = prep.executeUpdate();
prep.close();
conn.close();
return rowsAffected > 0;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 根据食品名称和商家ID删除食品
* 这个方法通过删除数据库中的特定食品记录来删除食品
*
* @param foodName 食品的名称
* @param business 商家的唯一标识ID用于确定食品属于哪个商家
* @return 如果删除成功则返回true否则返回false
*/
@Override
public boolean deleteFoodName (String foodName, Business business) {
try{
Connection conn = JDBC.getConnection();
String sql = "DELETE FROM food WHERE businessId = ? AND foodName = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, business.getBusinessId());
prep.setString(2, foodName);
int rowsAffected = prep.executeUpdate();
prep.close();
conn.close();
return rowsAffected > 0;
} catch (Exception e){
e.printStackTrace();
}
return false;
}
}

15
src/data/AdminMap.java Normal file
View File

@ -0,0 +1,15 @@
package data;
import java.util.HashMap;
import java.util.Map;
import po.Admin;
public class AdminMap {
public static final Map<Integer, Admin> ADMIN_MAP = new HashMap<>();
static {
ADMIN_MAP.put(1, new Admin(1, "jrnitre", "123"));
}
}

33
src/jdbc/JDBC.java Normal file
View File

@ -0,0 +1,33 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package jdbc;
import java.sql.*;
public class JDBC {
// ???????
private static final String URL = "jdbc:mysql://124.220.110.170:3306/jrnitre";
private static final String user = "jrnitre";
private static final String Password = "npgt1365";
/**
* ?????????????
* ?????????????MySQL JDBC???????????????????????????????????????????????????
* ?????????????????????????????????????????????
*
* @return Connection ????????????????????
* @throws RuntimeException ????????????????????????????????????
*/
public static Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, user, Password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
throw new RuntimeException("????????????", e);
}
}
}

60
src/po/Admin.java Normal file
View File

@ -0,0 +1,60 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package po;
public class Admin {
// 成员变量
private Integer adminId; // 管理员 ID
private String adminName; // 管理员名
private String adminPassword; // 管理员密码
// 有参构造方法
// 初始化管理员
public Admin (Integer id, String name, String passworld){
super();
adminId = id;
adminName = name;
adminPassword = passworld;
}
// 无参构造方法
public Admin (){
super();
}
// 拷贝构造方法
public Admin (Admin cpAdmin){
adminId = cpAdmin.adminId;
adminName = cpAdmin.adminName;
adminPassword = cpAdmin.adminPassword;
}
// getter
public Integer getAdminId(){
return adminId;
}
public String getAdminName(){
return adminName;
}
public String getAdminPassword(){
return adminPassword;
}
// setter
public void setAdminId(Integer id){
adminId = id;
}
public void setAdminName(String name){
adminName = name;
}
public void setAdminPassword(String password){
adminPassword = password;
}
}

96
src/po/Business.java Normal file
View File

@ -0,0 +1,96 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package po;
public class Business {
// 成员变量
private Integer businessId; // 商家 ID
private String businessName; // 商家名称
private String businessPassword; // 商家密码
private String businessAddress; // 商家地址
private String businessExplain; // 商家介绍
private double businessStarPrice; // 商家 起送费
private double businessDeliveryPrice; // 商家 配送费
// 拷贝构造方法
public Business (Business cpBusiness){
this.businessId = cpBusiness.getBusinessId();
this.businessName = cpBusiness.getBusinessName();
this.businessPassword = cpBusiness.getBusinessPassword();
this.businessAddress = cpBusiness.getBusinessAddress();
this.businessExplain = cpBusiness.getBusinessExplain();
this.businessStarPrice = cpBusiness.getBusinessStarPrice();
this.businessDeliveryPrice = cpBusiness.getBusinessDeliveryPrice();
}
// 无参构造方法
public Business () { super(); }
// setter
public void setBusinessId(Integer id){
businessId = id;
}
public void setBusinessName(String name){
businessName = name;
}
public void setBusinessPassword(String password){
businessPassword = password;
}
public void setBusinessAddress(String address){
businessAddress = address;
}
public void setBusinessExplain(String explain){
businessExplain = explain;
}
public void setBusinessStarPrice(double starPrice){
businessStarPrice = starPrice;
}
public void setBusinessDeliveryPrice(double deliveryPrice){
businessDeliveryPrice = deliveryPrice;
}
// getter
public Integer getBusinessId(){
return businessId;
}
public String getBusinessPassword(){
return businessPassword;
}
public String getBusinessName(){
return businessName;
}
public String getBusinessAddress(){
return businessAddress;
}
public String getBusinessExplain(){
return businessExplain;
}
public double getBusinessStarPrice(){
return businessStarPrice;
}
public double getBusinessDeliveryPrice(){
return businessDeliveryPrice;
}
// TODO tototototoString !!!
@Override
public String toString() {
return super.toString();
}
}

49
src/po/Food.java Normal file
View File

@ -0,0 +1,49 @@
/*
* Date: 2024-06-18
* Design By JRNitre
* */
package po;
public class Food {
// 成员变量
private int foodId; // 食品编号
private String foodName; // 食品名称
private String foodExplain; // 食品说明
private double foodPrice; // 食品价格
private int businessId; // 所属商家编号
// setter
public void setFoodId(int id){
this.foodId = id;
}
public void setFoodName(String name){
this.foodName = name;
}
public void setFoodExplain(String explain){
this.foodExplain = explain;
}
public void setFoodPrice(double price){
this.foodPrice = price;
}
public void setBusinessId(int id){
this.businessId = id;
}
// getter
public int getFoodId(){
return this.foodId;
}
public String getFoodName(){
return this.foodName;
}
public String getFoodExplain(){
return this.foodExplain;
}
public double getFoodPrice(){
return this.foodPrice;
}
public int getBusinessId(){
return this.businessId;
}
}