Flight information management system (JDBC)


Mission overview

In order to improve user experience, an airline hopes to build a flight information system. Users can operate flight information according to their needs:

  1. Display the flight information system main menu
  2. Check all flight information
  3. Search by departure time
  4. Search by destination
  5. Delete flight
  6. Update flight
  7. Exit system

specific requirement

By operating the database through java code, users can perform corresponding operations on the console.


Involving knowledge points

1. SQL language and basic operations

2. JDBC (Java Database Connection)

3. Use of custom tool classes and properties configuration files

4. JDBC connection pool


Task process

1. Create the database table airinfo, add test data, and the primary key will increase automatically.

2. Create a new object package pojo, create the entity class AirInfo, and provide the required constructor and setter/getter methods according to the business.

3. Create a new toolkit utils, create the DBUtils class, encapsulate database operation methods, and implement database connection and shutdown functions.

4. Create a new exception package exception and create a custom exception class OutNumberBoundException

5. Create a new view package view and create the AirInfoView class to prompt the user for input and output.

6. Create a new data operation package dao, create the AirInfoDao interface, and define methods for querying all flights, querying flights by departure time and destination, deleting flights, and updating flights.

7. In the data operation package dao, create the AirInfoDaoImpl class, inherit the DBUtils class, implement the AirInfoDao interface, and use JDBC to complete the corresponding database operations.

8. Create a new test package test, create the Platform class, complete the operations of displaying message information on the console and adding messages by users, and start and run the system.

Insert image description here


Ideas and code implementation

1. Toolkit

Create a utils package, create a new class DBUtils, and create a new configuration file db.properties

properties configuration file

Use ResourceBundle to access local resources and read the values ​​we need from them

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username=root
password=123456

DBUtils

JDBC tool class encapsulates methods for operating sql, so static methods are recommended.

  • Variable definitions
	//定义需要的工具类对象(变量定义)
    protected static Connection connection = null;
    protected static PreparedStatement pps = null;//后续都是用预状态通道来实现
    protected static ResultSet rs = null;//结果集
    protected static int count = 0;//受影响的行数
    //登录的用户名和密码
    private static String username;
    private static String password;
    private static String url;
    private static String driverName;
    //Druid连接池
    private static DruidDataSource druidDataSource = new DruidDataSource();
  • Load driver
	//加载驱动
    static {
    
    
        //Druid
        ResourceBundle bundle = ResourceBundle.getBundle("db");//参数只写属性文件名,不需要写后缀
        //加载属性文件
        driverName = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverName);
    }
  • get link
    protected static Connection getConnection() {
    
    
        try {
    
    
            connection = druidDataSource.getConnection();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return connection;
    }
  • Get the pre-state channel and bind parameters
	//得到预状态通道
    protected static PreparedStatement getPps(String sql) {
    
    
        try {
    
    
            getConnection();
            pps = connection.prepareStatement(sql);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return pps;
    }
    
    //绑定参数,给占位符赋值,list中保存的是给占位符所赋的值
    private static void setParams(List list) {
    
    
        try {
    
    
            if (list != null && list.size() > 0) {
    
    //集合中有内容
                for (int i = 0; i < list.size(); i++) {
    
    
                    pps.setObject(i + 1, list.get(i));//赋值,位置从1开始所以为i+1
                }
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
  • addition, deletion, modification
    protected static int update(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            count = pps.executeUpdate();//pps.executeUpdate()执行sql语句,返回受影响的行数
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return count;//返回受影响的行数
    }
  • data query
	protected static ResultSet query(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            rs = pps.executeQuery();//pps.executeUpdate()执行sql语句,返回结果集
            return rs;//返回结果集
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }
  • Close resource
    protected static void closeAll() {
    
    
        try {
    
    
            if (rs != null) {
    
    
                rs.close();
            }
            if (pps != null) {
    
    
                pps.close();
            }
            if (connection != null) {
    
    
                connection.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

2. Custom exceptions

Create an exception package and create a new class OutNumberBoundException

OutNumberBoundException

public class OutNumberBoundException extends Throwable {
    
    
    public OutNumberBoundException(String s) {
    
    
        super(s);
    }
}

3. Object

Create a pojo package and create a new class AirInfo

The AirInfo class corresponds to the data table airinfo, soClass attribute name = table field name

The airinfo table is as follows:
Insert image description here

AirInfo

  • Define properties and set and get values ​​with setters and getters
    private Integer number;
    private String airid;
    private String address;
    private Date flydate;
    
	public Integer getNumber() {
    
    
        return number;
    }

    public void setNumber(Integer number) {
    
    
        this.number = number;
    }

    public String getAirId() {
    
    
        return airid;
    }

    public void setAirId(String airid) {
    
    
        this.airid = airid;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public Date getFlyDate() {
    
    
        return flydate;
    }

    public void setFlyDate(Date flydate) {
    
    
        this.flydate = flydate;
    }
  • Define no-parameter and full-parameter constructors
	public AirInfo() {
    
    
    }

    public AirInfo(Integer number, String airid, String address, Date flydate) {
    
    
        this.number = number;
        this.airid = airid;
        this.address = address;
        this.flydate = flydate;
    }
  • Override the toString() method to convert the information into a string
	@Override
    public String toString() {
    
    
        return number + " " + '\t' + airid + " "  + '\t' + address + " "  + '\t' + flydate;
    }


4. View analysis

Mainly responsible for data input and output module

Create a view package and create a new class AirInfoView

AirInfoView

  • Enter the system interface main menu
    public static int mainMenu() {
    
    
        int mainNum = 0;
        do {
    
    
            System.out.println("----------欢迎使用航班信息管理系统----------");
            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("0.退出系统");
            String s = input.nextLine();
            try {
    
    
                mainNum = AirInfoDaoImpl.validNum(s, 0, 5);//判断输入是否有效
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
    
    
                System.out.println(e.getMessage());
            }
        } while (true);
        return mainNum;
    }
  • Check all flight information
    /**
     * 查询所有的航班信息
     */
    public static void printAllAir(List<AirInfo> airInfoList) {
    
    
        System.out.println("航班信息如下:");
        System.out.println("编号\t航班号 \t目的地\t\t起飞日期");
        for (AirInfo airInfo : airInfoList) {
    
    
            printAirInfo(airInfo);//打印单条航班信息
        }
    }
    
	/**
     * 打印单条航班信息
     */
    public static void printAirInfo(AirInfo a) {
    
    
        System.out.println(a.toString());
    }
  • Check flights by departure time
	public static String findByDate() {
    
    
        System.out.print("请输入起飞时间(form:year-month-day):");
        String s = input.nextLine();
        return s;
    }
  • Search flights by destination
    public static String findByAddress() {
    
    
        System.out.print("请输入航班的目的地:");
        String s = input.nextLine();
        return s;
    }
  • Delete flight
    /**
     * (根据航班号)删除航班
     */
    public static String deleteByAirId() {
    
    
        System.out.print("请输入要删除航班的航班号:");
        String s = input.nextLine();
        return s;
    }

	/**
     * 是否删除航班
     */
    public static int isDelete() {
    
    
        int num = 0;
        do {
    
    
            System.out.println("是否确认删除?");
            System.out.println("1.确认删除");
            System.out.println("0.取消操作");
            String s = input.nextLine();
            try {
    
    
                num = AirInfoDaoImpl.validNum(s, 0, 1);
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
    
    
                System.out.println(e.getMessage());
            }
        } while (true);
        return num;
    }
  • Update flight
	/**
     * (根据编号)更新航班
     */
    public static int updateByNumber() {
    
    
        System.out.print("请输入要更新航班的编号:");
        String s = input.nextLine();
        int num = Integer.parseInt(s);
        return num;
    }

    /**
     * 输入新的航班目的地
     */
    public String updateAddress() {
    
    
        System.out.print("请输入新的航班目的地:");
        String s = input.nextLine();
        return s;
    }

    /**
     * 输入新的航班日期
     */
    public String updateDate() {
    
    
        System.out.print("请输入新的航班起飞时间:");
        String s = input.nextLine();
        return s;
    }
  • Entering and exiting the system
	/**
     * 进入系统
     */
    public static void welcome() {
    
    
        System.out.println("欢迎进入航班信息管理系统!");
    }
    
	/**
     * 退出系统
     */
    public static void bye() {
    
    
        System.out.println("感谢使用航班信息管理系统!");
    }

5. Data access

Module mainly responsible for data processing

Create a dao package, create a new AirInfoDao interface, create a new AirInfoDaoImpl class that inherits the DBUtils class, implements the AirInfoDao interface, and uses JDBC to complete the corresponding database operations.

AirInfoDao

Define abstract methods for querying all flights, querying flights by departure time and destination, deleting flights, and updating flights

  • Check all flight information
    List<AirInfo> getAirList();
  • Check flights by departure time
    List<AirInfo> findByDate(String date);
  • Search flights by destination
    List<AirInfo> findByAddress(String address);
  • Delete flight
    int deleteByAirId(String airid);
  • Update flight
    int updateAirInfo(int num, String newAddress, String newDate);

AirInfoDaoImpl

Concretely implement the abstract methods defined in the interface

  • Determine whether the input is a number and within the valid range
	public static int validNum(String s, int begin, int end) throws NumberFormatException, OutNumberBoundException {
    
    
        try {
    
    
            int num = Integer.parseInt(s);
            if (num < begin || num > end) {
    
    
                throw new OutNumberBoundException("数字的范围必须在" + begin + "和" + end + "之间");
            }
            return num;
        } catch (NumberFormatException e) {
    
    
            throw new NumberFormatException("输入的必须是数字!");
        }
    }

  • Check all flight information
	@Override
    public List<AirInfo> getAirList() {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo ";
            ResultSet resultSet = query(sql, null);
            while (resultSet.next()) {
    
    
                AirInfo info = new AirInfo();
                info.setNumber(resultSet.getInt("number"));
                info.setAirId(resultSet.getString("airid"));
                info.setAddress(resultSet.getString("address"));
                info.setFlyDate(resultSet.getDate("flydate"));
                arrayList.add(info);
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }
  • Check flights by departure time
	@Override
    public List<AirInfo> findByDate(String date) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where flydate = ?";
            ArrayList param = new ArrayList();
            param.add(date);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }
  • Search flights by destination
	@Override
    public List<AirInfo> findByAddress(String address) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where address like ?";
            ArrayList param = new ArrayList();
            param.add("%" + address + "%");
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }
  • Delete flight
	/**
     * (根据航班号)删除航班
     */
    @Override
    public int deleteByAirId(String airid) {
    
    
        int count = 0;
        try {
    
    
            String sql = "delete from airinfo where airid = ?";
            ArrayList param = new ArrayList();
            param.add(airid);
            count = update(sql, param);
        } finally {
    
    
            closeAll();
        }
        return count;//返回受影响的行数
    }

    /**
     * (根据航班号)查询航班是否存在
     * 可能该航班存在多个时间点,因此用list存储查找到的信息
     */
    public List<AirInfo> findById(String airid) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where airid = ?";
            ArrayList param = new ArrayList();
            param.add(airid);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }
  • Update flight
	/**
     * (根据编号)更新航班
     */
    @Override
    public int updateAirInfo(int num, String newAddress, String newDate) {
    
    
        int count = 0;
        try {
    
    
            String sql = "update airinfo set address = ? ,flydate = ? where number = ?";
            ArrayList param = new ArrayList();
            param.add(newAddress);
            param.add(newDate);
            param.add(num);
            count = update(sql, param);
        } finally {
    
    
            closeAll();
        }
        return count;//返回受影响的行数
    }

    /**
     * 根据编号查找航班是否存在
     */
    public AirInfo findByNumber(int number) {
    
    
        AirInfo info = new AirInfo();
        try {
    
    
            String sql = "select* from airinfo where number = ?";
            ArrayList param = new ArrayList();
            param.add(number);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                info.setNumber(resultSet.getInt("number"));
                info.setAirId(resultSet.getString("airid"));
                info.setAddress(resultSet.getString("address"));
                info.setFlyDate(resultSet.getDate("flydate"));
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return info;
    }

6. Main interface

Create a test package and create a new class Platform

Platform

  • Use the system main menu to enter the corresponding function interface
    public static void main(String[] args) {
    
    
        v.welcome();//进入界面

        //调用主菜单进入相应的功能界面
        m:
        while (true) {
    
    
            int mainNum = v.mainMenu();//调用主菜单
            switch (mainNum) {
    
    
                case 0://结束使用
                    break m;
                case 1://查询所有的航班信息
                    printAllAir();
                    break;
                case 2://按起飞时间查询
                    findByDate();
                    break;
                case 3://按目的地查询
                    findByAddress();
                    break;
                case 4://(根据航班号)删除航班
                    deleteByAirId();
                    break;
                case 5://(根据航班号)更新航班
                    updateAirInfo();
                    break;
            }
        }// end while

        v.bye();//退出系统
        
    }//end main
  • Check all flight information
    public static void printAllAir() {
    
    
        v.printAllAir(dao.getAirList());
    }
  • Check flights by departure time
	public static void findByDate() {
    
    
        String date = v.findByDate();
        List<AirInfo> infos = dao.findByDate(date);
        if (infos != null) {
    
    
            v.printAllAir(infos);
        } else {
    
    
            System.out.println("该时间暂未航班信息!");
        }
    }
  • Search flights by destination
	public static void findByAddress() {
    
    
        String address = v.findByAddress();
        List<AirInfo> infos = dao.findByAddress(address);
        if (infos != null) {
    
    
            v.printAllAir(infos);
        } else {
    
    
            System.out.println("暂未到达该目的地的航班信息!");
        }
    }

  • Delete flight (based on flight number)
    public static void deleteByAirId() {
    
    
        String airId = v.deleteByAirId();
        List<AirInfo> infos = dao.findById(airId);
        if (infos != null) {
    
    
            v.printAllAir(infos);
            if (v.isDelete() == 1) {
    
    
                int count = dao.deleteByAirId(airId);
                System.out.println(count + "行受影响,删除成功!");
            } else {
    
    
                System.out.println("取消成功!");
            }
        } else {
    
    
            System.out.println("该航班不存在!");
        }
    }
  • Update flight (according to number)
    public static void updateAirInfo() {
    
    
        int num = v.updateByNumber();//输入要更新的航班的编号
        AirInfo info = dao.findByNumber(num);
        if (info != null) {
    
    
            System.out.println("要更新的航班信息如下:");
            v.printAirInfo(info);//打印所有该航班号的航班信息
            String newAddress = v.updateAddress();
            String newDate = v.updateDate();
            dao.updateAirInfo(num, newAddress, newDate);
            System.out.println("更新成功!");
        } else {
    
    
            System.out.println("暂未此航班号的航班信息!");
        }
    }

The complete code is as follows

1. Toolkit

properties configuration file

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username=root
password=123456

DBUtils

public class DBUtils {
    
    
    //1.定义需要的工具类对象(变量定义)
    protected static Connection connection = null;
    protected static PreparedStatement pps = null;//后续都是用预状态通道来实现
    protected static ResultSet rs = null;//结果集
    protected static int count = 0;//受影响的行数

    //登录的用户名和密码
    private static String username;
    private static String password;
    private static String url;
    private static String driverName;
    //Druid
    private static DruidDataSource druidDataSource = new DruidDataSource();

    //2.加载驱动
    static {
    
    
        //Druid
        ResourceBundle bundle = ResourceBundle.getBundle("db");//参数只写属性文件名,不需要写后缀
        //加载属性文件
        driverName = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverName);

    }


    //3.获得连接
    protected static Connection getConnection() {
    
    
        try {
    
    
            connection = druidDataSource.getConnection();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return connection;
    }


    //4.得到预状态通道
    protected static PreparedStatement getPps(String sql) {
    
    
        try {
    
    
            getConnection();//insert into users values(?,?,?,?,)
            pps = connection.prepareStatement(sql);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return pps;
    }


    //5.绑定参数,给占位符赋值,list中保存的是给占位符所赋的值
    private static void setParams(List list) {
    
    
        try {
    
    
            if (list != null && list.size() > 0) {
    
    //集合中有内容
                for (int i = 0; i < list.size(); i++) {
    
    
                    pps.setObject(i + 1, list.get(i));//赋值,位置从1开始所以为i+1
                }
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }


    //6.增删改
    protected static int update(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            count = pps.executeUpdate();//pps.executeUpdate()执行sql语句,返回受影响的行数
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return count;//返回受影响的行数
    }


    //7.查询
    protected static ResultSet query(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            rs = pps.executeQuery();//pps.executeUpdate()执行sql语句,返回结果集
            return rs;//返回结果集
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }


    //8.关闭资源
    protected static void closeAll() {
    
    
        try {
    
    
            if (rs != null) {
    
    
                rs.close();
            }
            if (pps != null) {
    
    
                pps.close();
            }
            if (connection != null) {
    
    
                connection.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }


}

2. Custom exceptions

OutNumberBoundException

public class OutNumberBoundException extends Throwable {
    
    
    public OutNumberBoundException(String s) {
    
    
        super(s);
    }
}

3. Object

AirInfo

public class AirInfo {
    
    
    private Integer number;
    private String airid;
    private String address;
    private Date flydate;

    public AirInfo() {
    
    
    }

    public AirInfo(Integer number, String airid, String address, Date flydate) {
    
    
        this.number = number;
        this.airid = airid;
        this.address = address;
        this.flydate = flydate;
    }

    public Integer getNumber() {
    
    
        return number;
    }

    public void setNumber(Integer number) {
    
    
        this.number = number;
    }

    public String getAirId() {
    
    
        return airid;
    }

    public void setAirId(String airid) {
    
    
        this.airid = airid;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public Date getFlyDate() {
    
    
        return flydate;
    }

    public void setFlyDate(Date flydate) {
    
    
        this.flydate = flydate;
    }

    @Override
    public String toString() {
    
    
        return number + " " + '\t' + airid + " "  + '\t' + address + " "  + '\t' + flydate;
    }


}

4. View analysis

AirInfoView

public class AirInfoView {
    
    

    public static Scanner input = new Scanner(System.in);

    /**
     * 进入系统
     */
    public static void welcome() {
    
    
        System.out.println("欢迎进入航班信息管理系统!");
    }

    /**
     * 主菜单,系统界面
     */
    public static int mainMenu() {
    
    
        int mainNum = 0;
        do {
    
    
            System.out.println("----------欢迎使用航班信息管理系统----------");
            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("0.退出系统");
            String s = input.nextLine();
            try {
    
    
                mainNum = AirInfoDaoImpl.validNum(s, 0, 5);
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
    
    
                System.out.println(e.getMessage());
            }
        } while (true);
        return mainNum;
    }

    /**
     * 1、查询所有的航班信息
     */
    public static void printAllAir(List<AirInfo> airInfoList) {
    
    
        System.out.println("航班信息如下:");
        System.out.println("编号\t航班号 \t目的地\t\t起飞日期");
        for (AirInfo airInfo : airInfoList) {
    
    
            printAirInfo(airInfo);
        }
    }

    /**
     * 打印单条航班信息
     */
    public static void printAirInfo(AirInfo a) {
    
    
        System.out.println(a.toString());
    }

    /**
     * 2、按起飞时间查询
     */
    public static String findByDate() {
    
    
        System.out.print("请输入起飞时间(form:year-month-day):");
        String s = input.nextLine();
        return s;
    }

    /**
     * 3、按目的地查询
     */
    public static String findByAddress() {
    
    
        System.out.print("请输入航班的目的地:");
        String s = input.nextLine();
        return s;
    }

    /**
     * 4、(根据航班号)删除航班
     */
    public static String deleteByAirId() {
    
    
        System.out.print("请输入要删除航班的航班号:");
        String s = input.nextLine();
        return s;
    }

    /**
     * 是否删除航班
     */
    public static int isDelete() {
    
    
        int num = 0;
        do {
    
    
            System.out.println("是否确认删除?");
            System.out.println("1.确认删除");
            System.out.println("0.取消操作");
            String s = input.nextLine();
            try {
    
    
                num = AirInfoDaoImpl.validNum(s, 0, 1);
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
    
    
                System.out.println(e.getMessage());
            }
        } while (true);
        return num;
    }

    /**
     * 5、根据编号更新航班
     */
    public static int updateByNumber() {
    
    
        System.out.print("请输入要更新航班的编号:");
        String s = input.nextLine();
        int num = Integer.parseInt(s);
        return num;
    }

    /**
     * 输入新的航班目的地
     */
    public String updateAddress() {
    
    
        System.out.print("请输入新的航班目的地:");
        String s = input.nextLine();
        return s;
    }

    /**
     * 输入新的航班日期
     */
    public String updateDate() {
    
    
        System.out.print("请输入新的航班起飞时间:");
        String s = input.nextLine();
        return s;
    }


    /**
     * 退出系统
     */
    public static void bye() {
    
    
        System.out.println("感谢使用航班信息管理系统!");
    }

}


5. Data access

AirInfoDao

/**
 * 定义查询所有航班,按日期和目的地查询航班,删除航班,更新航班的方法
 */
public interface AirInfoDao {
    
    
    /**
     * 1、查询所有的航班信息
     */
    List<AirInfo> getAirList();

    /**
     * 2、按起飞时间查询
     */
    List<AirInfo> findByDate(String date);

    /**
     * 3、按目的地查询
     */
    List<AirInfo> findByAddress(String address);

    /**
     * 4、(根据航班号)删除航班
     */
    int deleteByAirId(String airid);

    /**
     * 5、更新航班
     */
    int updateAirInfo(int num, String newAddress, String newDate);


}


AirInfoImpl

/**
 * 使用 JDBC 完成相应数据库操作
 */
public class AirInfoDaoImpl extends DBUtils implements AirInfoDao {
    
    

    /**
     * 判断输入是否为数字、是否在有效范围内
     */
    public static int validNum(String s, int begin, int end) throws NumberFormatException, OutNumberBoundException {
    
    
        try {
    
    
            int num = Integer.parseInt(s);
            if (num < begin || num > end) {
    
    
                throw new OutNumberBoundException("数字的范围必须在" + begin + "和" + end + "之间");
            }
            return num;
        } catch (NumberFormatException e) {
    
    
            throw new NumberFormatException("输入的必须是数字!");
        }
    }

    /**
     * 1、查询所有的航班信息
     */
    @Override
    public List<AirInfo> getAirList() {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo ";
            ResultSet resultSet = query(sql, null);
            while (resultSet.next()) {
    
    
                AirInfo info = new AirInfo();
                info.setNumber(resultSet.getInt("number"));
                info.setAirId(resultSet.getString("airid"));
                info.setAddress(resultSet.getString("address"));
                info.setFlyDate(resultSet.getDate("flydate"));
                arrayList.add(info);
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }


    /**
     * 2、按起飞时间查询
     */
    @Override
    public List<AirInfo> findByDate(String date) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where flydate = ?";
            ArrayList param = new ArrayList();
            param.add(date);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }

    /**
     * 3、按目的地查询
     */
    @Override
    public List<AirInfo> findByAddress(String address) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where address like ?";
            ArrayList param = new ArrayList();
            param.add("%" + address + "%");
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }

    /**
     * 4、(根据航班号)删除航班
     */
    @Override
    public int deleteByAirId(String airid) {
    
    
        int count = 0;
        try {
    
    
            String sql = "delete from airinfo where airid = ?";
            ArrayList param = new ArrayList();
            param.add(airid);
            count = update(sql, param);
        } finally {
    
    
            closeAll();
        }
        return count;//返回受影响的行数
    }

    /**
     * (根据航班号)查询航班是否存在
     * 可能该航班存在多个时间点,因此用list存储查找到的信息
     */
    public List<AirInfo> findById(String airid) {
    
    
        ArrayList arrayList = new ArrayList();
        try {
    
    
            String sql = "select* from airinfo where airid = ?";
            ArrayList param = new ArrayList();
            param.add(airid);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                do {
    
    
                    AirInfo info = new AirInfo();
                    info.setNumber(resultSet.getInt("number"));
                    info.setAirId(resultSet.getString("airid"));
                    info.setAddress(resultSet.getString("address"));
                    info.setFlyDate(resultSet.getDate("flydate"));
                    arrayList.add(info);
                } while (resultSet.next());
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return arrayList;
    }


    /**
     * 5、(根据编号)更新航班
     */
    @Override
    public int updateAirInfo(int num, String newAddress, String newDate) {
    
    
        int count = 0;
        try {
    
    
            String sql = "update airinfo set address = ? ,flydate = ? where number = ?";
            ArrayList param = new ArrayList();
            param.add(newAddress);
            param.add(newDate);
            param.add(num);
            count = update(sql, param);
        } finally {
    
    
            closeAll();
        }
        return count;//返回受影响的行数
    }

    /**
     * 根据编号查找航班是否存在
     */
    public AirInfo findByNumber(int number) {
    
    
        AirInfo info = new AirInfo();
        try {
    
    
            String sql = "select* from airinfo where number = ?";
            ArrayList param = new ArrayList();
            param.add(number);
            ResultSet resultSet = query(sql, param);
            if (resultSet.next() == false) {
    
    //查询结果为空
                return null;
            } else {
    
    //查询结果非空
                info.setNumber(resultSet.getInt("number"));
                info.setAirId(resultSet.getString("airid"));
                info.setAddress(resultSet.getString("address"));
                info.setFlyDate(resultSet.getDate("flydate"));
            }//end if
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return info;
    }



}


6. Main interface

Platform

public class Platform {
    
    
    public static AirInfoView v = new AirInfoView();
    public static AirInfoDaoImpl dao = new AirInfoDaoImpl();
    public static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
    
    
        v.welcome();

        //调用主菜单进入相应的功能界面
        m:
        while (true) {
    
    
            int mainNum = v.mainMenu();//调用主菜单
            switch (mainNum) {
    
    
                case 0://结束使用
                    break m;
                case 1://查询所有的航班信息
                    printAllAir();
                    break;
                case 2://按起飞时间查询
                    findByDate();
                    break;
                case 3://按目的地查询
                    findByAddress();
                    break;
                case 4://(根据航班号)删除航班
                    deleteByAirId();
                    break;
                case 5://(根据航班号)更新航班
                    updateAirInfo();
                    break;
            }
        }// end while

        v.bye();
    }//end main


    /**
     * 1、查询所有航班信息
     */
    public static void printAllAir() {
    
    
        v.printAllAir(dao.getAirList());
    }


    /**
     * 2、按起飞时间查询
     */
    public static void findByDate() {
    
    
        String date = v.findByDate();
        List<AirInfo> infos = dao.findByDate(date);
        if (infos != null) {
    
    
            v.printAllAir(infos);
        } else {
    
    
            System.out.println("该时间暂未航班信息!");
        }
    }


    /**
     * 3、按目的地查询
     */
    public static void findByAddress() {
    
    
        String address = v.findByAddress();
        List<AirInfo> infos = dao.findByAddress(address);
        if (infos != null) {
    
    
            v.printAllAir(infos);
        } else {
    
    
            System.out.println("暂未到达该目的地的航班信息!");
        }
    }


    /**
     * 4、(根据航班号)删除航班
     */
    public static void deleteByAirId() {
    
    
        String airId = v.deleteByAirId();
        List<AirInfo> infos = dao.findById(airId);
        if (infos != null) {
    
    
            v.printAllAir(infos);
            if (v.isDelete() == 1) {
    
    
                int count = dao.deleteByAirId(airId);
                System.out.println(count + "行受影响,删除成功!");
            } else {
    
    
                System.out.println("取消成功!");
            }
        } else {
    
    
            System.out.println("该航班不存在!");
        }
    }


    /**
     * 5、更新航班(由于编号唯一,因此根据编号更新)
     */
    public static void updateAirInfo() {
    
    
        int num = v.updateByNumber();//输入要更新的航班的编号
        AirInfo info = dao.findByNumber(num);
        if (info != null) {
    
    
            System.out.println("要更新的航班信息如下:");
            v.printAirInfo(info);//打印所有该航班号的航班信息
            String newAddress = v.updateAddress();
            String newDate = v.updateDate();
            dao.updateAirInfo(num, newAddress, newDate);
            System.out.println("更新成功!");
        } else {
    
    
            System.out.println("暂未此航班号的航班信息!");
        }
    }


}//end class

Guess you like

Origin blog.csdn.net/m0_50609545/article/details/119846855