前言: 上篇文章使用Java基于MVC模式开发一个简单商品管理系统给很多java web初学者(1-3个月)提供了些许帮助,不久前又有读者问我能不能开发一个纯java控制台版的简易管理系统,遂写下此文。
持续更新……
2019年12月25日 23:09:25
文章已贴上全部源码
效果图:
开发环境:
- Eclipse Oxygen
- JDK 1.8.0_112
打包全部源码:
地址: https://pan.baidu.com/s/1tXr8Y_32WlEXYZrMBWKK0A
密钥: 6rpa
功能:
- 商品查询(全部查询、根据商品名模糊查询、根据商品产地模糊查询)
- 商品添加(输入商品名、商品产地、商品价格即可添加)
- 商品删除(输入商品编号,根据商品编号进行删除)
- 商品更新(输入待更新商品的编号,再输入新名称,新产地信息,新价格,完成更新)
不足:
- 控制台版本,格式化的输出需要优化,用户操作需要优化,时间有限,先把功能完成了
优点:
- 适用于java初学者,学习JDBC相关操作,理解增加(Insert)、删除(Delete)、修改(Update)、查询(Retrive)的过程。
- 代码根据之前MVC版本的DAO代码改造,避免了一个业务方法中写过多的DAO代码,一定程度上降低了代码的耦合性,基本符合开闭原则,可快速进行功能迭代,添加相关DAO实现后,使用工厂类注册,方便业务层调用等。
项目树结构:
项目树结构,及jar包引用:
数据表结构:
示例数据:
FAQ:
-
如何构建项目,运行起来?
使用一个集成开发环境(如:Eclipse、MyEclipse、Intellij IDEA等)创建java project
→ 将本文src
中的全部包导入 → 为项目引用jdbc jar包 → 使用数据库脚本创建数据库表结构→检查数据库链接字符串 → 运行test类
检查数据库连接是否正常,运行程序com.mysql.jdbc.JDBC4Connection@2c2a5319
看到此输出,则证明数据库链接正常 -
注意事项有哪些?
暂未优化控制台输出的版本,因此格式稍有凌乱,建议使用鼠标将光标定位到末尾输入,则可以看到较为整齐的输出
如果使用了本文中已打包的程序,注意配置jdk、数据库连接jar包的引用
源码:
1.实体类
package com.zjl.bean;
/**
* 商品实体类
* @author Administrator
*
*/
public class Product {
private int id;
private String name;
private String addr;
private double price;
public Product() {
super();
}
public Product(int id, String name, String addr, double price) {
super();
this.id = id;
this.name = name;
this.addr = addr;
this.price = price;
}
public Product(String name, String addr, double price) {
super();
this.name = name;
this.addr = addr;
this.price = price;
}
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 String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ",
name=" + name + ",
addr=" + addr + ",
price=" + price + "]";
}
}
2.数据库连接工具类
package com.zjl.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 数据库连接工具类
* @author Administrator
*
*/
public class ConnectDatabase {
private static final String DRIVER_STRING="com.mysql.jdbc.Driver";
private static final String URL_STRING="jdbc:mysql://47.105.159.27:3306/dbms";
private static final String USER_STRING="root";
private static final String PASS_STRING="admin";
public static Connection getConnection(){
Connection connection=null;
try {
Class.forName(DRIVER_STRING);
connection=DriverManager.getConnection(URL_STRING, USER_STRING, PASS_STRING);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public void realse(Connection conn,PreparedStatement ps,ResultSet rs){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.菜单及入口程序
package com.zjl.console;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.zjl.bean.Product;
import com.zjl.conn.ConnectDatabase;
import com.zjl.dao.DaoFactory;
import com.zjl.service.IProductDao;
public class Menu {
/**
* 控制台版,简易商品管理系统,含商品增加、删除、修改、查询
* 含用户登录
* 使用了mysql数据库
* 基于Java20180130MVC进行了改造,使用了原有的包结构和DAO
*/
static Scanner sc = new Scanner(System.in);
static List<Product> pList = new ArrayList<Product>();
static Product product = new Product();
static IProductDao pDao = DaoFactory.getProductDao();
public static void main(String[] args) {
menu();
}
public static void menu(){
while(true){
System.out.println("------商品管理系统-------");
System.out.println("1.测试数据库连接");
System.out.println("2.查询商品");
System.out.println("3.添加商品");
System.out.println("4.删除商品");
System.out.println("5.更新商品");
System.out.println("-------------------------");
System.out.println("请输入操作序号,按下回车,等待程序执行");
System.out.println();
int choice = sc.nextInt();
switch (choice) {
case 1:
// 1.测试数据库连接
System.out.println(ConnectDatabase.getConnection());
break;
case 2:
//2.查询商品
retrive();
break;
case 3:
//3.添加商品
insert();
break;
case 4:
//4.删除商品
delete();
break;
case 5:
//5.更新商品
update();
break;
}
}
}
/**
* 商品查询,全部查询,模糊查询
*/
private static void retrive() {
Map<String , Object> map =new HashMap<String, Object>();
System.out.println("1.查询全部商品");
System.out.println("2.按商品名称模糊查询");
System.out.println("3.按商品产地模糊查询");
int choice1 = sc.nextInt();
switch (choice1) {
case 1:
//查询全部
try {
map=null;
pList = pDao.queryProduct(map);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\t编号\t名称\t产地\t价格\n");
System.out.println("\t----------------------------------------------------");
for (int i = 0; i < pList.size(); i++) {
System.out.println(pList.get(i));
}
break;
case 2:
System.out.println("请输入商品名称,进行模糊查询:");
String name = sc.next();
//按名称模糊查询
map.put("name",name);
try {
pList = pDao.queryProduct(map);
System.out.println("\t编号\t名称\t产地\t价格\n");
for (int i = 0; i < pList.size(); i++) {
System.out.println(pList.get(i));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case 3:
//按产地模糊查询
System.out.println("请输入商品产地,进行模糊查询:");
String addr = sc.next();
map.put("addr", addr);
try {
pList = pDao.queryProduct(map);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("\t编号\t名称\t产地\t价格\n");
for (int i = 0; i < pList.size(); i++) {
System.out.println(pList.get(i));
}
}
}
/**
* 添加商品
*/
private static void insert() {
System.out.println("请输入要增加的商品信息:");
Scanner sc = new Scanner(System.in);
System.out.println("请输入商品名称:");
String name = sc.next();
System.out.println("请输入商品产地:");
String addr = sc.next();
System.out.println("请输入商品价格:");
Double price = sc.nextDouble();
product.setName(name);
product.setAddr(addr);
product.setPrice(price);
try {
if(pDao.insert(product)){
System.out.println("商品添加成功");
}else{
System.out.println("商品添加失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除商品
*/
private static void delete() {
System.out.println("请输入要删除的商品编号:");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
product.setId(id);
try {
if(pDao.delete(product)){
System.out.println("删除商品成功");
}else{
System.out.println("删除商品失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 更新商品
*/
private static void update() {
System.out.println("请输入要更新的商品编号:");
Scanner sc =new Scanner(System.in);
int id = sc.nextInt();
product.setId(id);
try {
product = pDao.queryById(product);
if(product==null){
System.out.println("数据不存在");
}else{
System.out.println("请输入新的商品名称:");
String name = sc.next();
System.out.println("请输入新的商品产地:");
String addr = sc.next();
System.out.println("请输入新的价格:");
Double price = sc.nextDouble();
product.setName(name);
product.setAddr(addr);
product.setPrice(price);
if(pDao.update(product)){
System.out.println("商品信息更新成功");
}else{
System.out.println("商品信息更新失败");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.工厂类
package com.zjl.dao;
import com.zjl.service.IProductDao;
import com.zjl.service.IUserDao;
/**
* DAO工厂类,为DAO调用者提供DAO实例对象
* @author Administrator
*
*/
public class DaoFactory {
public static IUserDao getUserDao(){
return new UserDaoImp();
}
public static IProductDao getProductDao(){
return new ProductImp();
}
}
5.商品DAO实现类
package com.zjl.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.zjl.bean.Product;
import com.zjl.bean.User;
import com.zjl.conn.ConnectDatabase;
import com.zjl.service.IProductDao;
/**
* 商品操作接口实现类,实现商品的增加、删除、更新、添加等操作
* @author Administrator
*
*/
public class ProductImp implements IProductDao {
PreparedStatement ps = null;
public boolean insert(Product p) {
String sql ="insert into product(name,addr,price) values(?,?,?)";
int n =0;
try{
ps = ConnectDatabase.getConnection().prepareStatement(sql);
ps.setString(1, p.getName());
ps.setString(2, p.getAddr());
ps.setDouble(3, p.getPrice());
n=ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
return n>0;
}
public boolean delete(Product p) {
String sql ="delete from product where id="+p.getId();
int n=0;
try{
ps=ConnectDatabase.getConnection().prepareStatement(sql);
n=ps.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
return n>0;
}
public boolean update(Product p) {
String sql = "update product set name=?,addr=?,price=? where id=?";
int n = 0;
try{
ps=ConnectDatabase.getConnection().prepareStatement(sql);
ps.setString(1, p.getName());
ps.setString(2, p.getAddr());
ps.setDouble(3, p.getPrice());
ps.setInt(4, p.getId());
n=ps.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
return n>0;
}
public List<Product> queryProduct(Map<String, Object> map) {
StringBuffer sql= new StringBuffer("select * from product where 1 =1");
// 判断Map,根据name模糊查询
if (map != null && map.get("name") != null) {// map不为空,即为模糊查询,append增加sql查询语句
sql.append(" and name like '").append("%").append(map.get("name")).append("%'");
// 根据addr模糊查询
} else if (map != null && map.get("addr") != null) {
sql.append(" and addr like '").append("%").append(map.get("addr")).append("%'");
}
List<Product> list = new ArrayList<Product>();
try{
ps = ConnectDatabase.getConnection().prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
while(rs.next()){
Product p = new Product();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAddr(rs.getString("addr"));
p.setPrice(rs.getDouble("price"));
list.add(p);
}
}
catch (Exception e) {
e.printStackTrace();
}
return list;
}
public Product queryById(Product p) {
Product product = null;
String sql = "select * from product where id="+p.getId();
try{
ps = ConnectDatabase.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()){
product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setAddr(rs.getString("addr"));
product.setPrice(rs.getDouble("price"));
}
}catch(Exception e){
e.printStackTrace();
}
return product;
}
}
6.商品DAO接口
package com.zjl.service;
import java.util.List;
import java.util.Map;
import com.zjl.bean.Product;
import com.zjl.bean.User;
/**商品操作接口
* @author Administrator
*
*/
public interface IProductDao {
public boolean insert(Product p);
public boolean delete(Product p);
public boolean update(Product p);
public List<Product> queryProduct(Map<String, Object> map);
public Product queryById(Product p);
}
7.测试类
package com.zjl.test;
import com.zjl.bean.User;
import com.zjl.conn.ConnectDatabase;
import com.zjl.dao.DaoFactory;
import com.zjl.service.IUserDao;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
ConnectDatabase conn = new ConnectDatabase();
System.out.println(conn);
IUserDao userDao =DaoFactory.getUserDao();
User user = new User("李四","123456");
System.out.println(userDao.insert(user));
}
}
8.sql脚本
/*
SQLyog v10.2
MySQL - 5.0.96-community-nt : Database - dbms
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`dbms` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `dbms`;
/*Table structure for table `product` */
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`addr` varchar(50) NOT NULL,
`price` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `product` */
insert into `product`(`id`,`name`,`addr`,`price`)
values (1,'冰红茶','广东',3.5),
(2,'娃哈哈','四川',1),
(3,'农夫山泉','泉州',2),
(4,'怡宝','武汉',2),
(5,'红牛','四川',4.5);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
后记:文章适用于初学java不久的读者,可以帮助理解jdbc 相关的Create、Retrive、Update、Delete相关操作,且代码经过精简,分离了DAO,冗余性较低。如在阅读中遇到疑惑、发现不恰当之处,欢迎指正。