主頁 >  其他 > java入門:用jdbc實作寵物商店管理系統續篇

java入門:用jdbc實作寵物商店管理系統續篇

2021-11-08 09:56:20 其他

用jdbc實作寵物商店管理系統
1,開發語言:java(JDK8)
2,開發工具:IntelliJ IDEA 2021.2.3
3,資料庫:MySQL
4,作業系統:Windows10
5,需要引入的jar包:mysql-connector-java-8.0.26.jar,下載地址:https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.26

因為上篇的資料庫檔案沒有了,重新建了資料庫以及修改了代碼里的腳本,用下面的新代碼就可以了
以下是運行圖片:
程式初始化
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
代碼實作:
邏輯代碼

package com.impl;

import com.dao.BaseDAO;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.InputMismatchException;
import java.util.Scanner;


/**
 * @author 咕嚕科
 * ClassName: PetManage
 * date: 2021/8/26 22:12
 * Description:
 * version 1.0
 */
public class PetManage extends BaseDAO {

    /**
     *
     */
    public void showAll() {
        showPetName();
        showPetOwner();
        showPetStore();
        login();
    }

    /**
     * 顯示寵物的姓名以及ID方法
     */
    public void showPetName() {
        conn = getConnection();
        String sql = "SELECT id,pet_name from pet";
        try {
            state = conn.prepareStatement(sql);
            rs = state.executeQuery();
            System.out.println("Wonderland醒來,所有寵物從MySQL中醒來");
            System.out.println("*************************************");
            int num = 1;
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("pet_name");
                System.out.println("第" + num + "只寵物,名字叫:" + name);
                num++;
            }
            System.out.println("*************************************\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeObject1();
        }

    }

    /**
     * 顯示寵物主人方法
     */
    public void showPetOwner() {
        conn = getConnection();
        String sql = "select id,owner_id,owner_name,money from pet_owner where owner_type = 1";
        try {
            state = conn.prepareStatement(sql);
            rs = state.executeQuery();
            System.out.println("所有寵物主人從MySQL中醒來");
            System.out.println("*************************************");
            int num = 1;
            while (rs.next()) {
                String name = rs.getString("owner_name");
                System.out.println("第" + num + "主人的名字叫:" + name);
                num++;
            }
            System.out.println("*************************************\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeObject1();
        }
    }

    /**
     * 顯示寵物商店方法
     */
    public void showPetStore() {
        conn = getConnection();
        String sql = "select id,owner_id,owner_name,money,address from pet_owner where owner_type = 2";
        try {
            state = conn.prepareStatement(sql);
            rs = state.executeQuery();
            System.out.println("所有寵物商店從MySQL中醒來");
            System.out.println("*************************************");
            int num = 1;
            while (rs.next()) {
                String storeName = rs.getString("owner_name");
                String storeAddress = rs.getString("address");
                System.out.println("第" + num + "個商店的名字叫: " + storeName + " ,地址在: " + storeAddress);
                num++;
            }
            System.out.println("*************************************\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeObject1();
        }
    }

    /**
     * 登錄界面選擇是主人登錄還是商店登錄方法
     */
    public void login() {

        System.out.println("請選擇輸入登錄模式\n1.寵物主人登錄\n2.寵物商店登錄\n3.退出系統\n-------------------");
        try {
            Scanner input = new Scanner(System.in);
            int choise = input.nextInt();
            if (choise < 1 || choise > 3) {
                System.out.println("輸入有誤,請重新選擇");
                login();
            } else {
                switch (choise) {
                    case 1:
                        petOwnerLogin();
                        break;
                    case 2:
                        petStoreLogin();
                        break;
                    case 3:
                        System.out.println("謝謝使用");
                        System.exit(0);
                        break;
                    default:
                        break;
                }
            }
        } catch (InputMismatchException e) {
            System.out.println("輸入有誤,請重新選擇");
            login();
        }

    }

    /**
     * 寵物主人登錄方法
     *
     * @return
     */
    public boolean petOwnerLogin() {
        boolean flag = false;
        try {
            Scanner input = new Scanner(System.in);
            System.out.println("請先登錄,請您先輸入主人的名字");
            String name = input.next();
            System.out.println("請您輸入主人的密碼:");
            String password = input.next();
            conn = getConnection();
            String sql = "SELECT owner_name,password from pet_owner where owner_name=? and password=?";
            try {
                state = conn.prepareStatement(sql);
                state.setString(1, name);
                state.setString(2, password);
                rs = state.executeQuery();
                if (rs.next()) {
                    System.out.println("---------恭喜您成功登錄!---------");
                    System.out.println("----------您的基本資訊---------");
                    conn = getConnection();
                    String sql2 = "SELECT id,owner_name,owner_id,password,money from pet_owner where owner_name=?";
//					state=conn.prepareStatement(sql2);
//					state.setString(1, name);
//					rs=state.executeQuery();
                    rs = search(sql2, name);
                    if (rs.next()) {
                        int uid = rs.getInt("owner_id");
                        String uname = rs.getString("owner_name");
                        Double uMoney = rs.getDouble("money");
                        System.out.println("登錄成功!!!!");
                        System.out.println("姓名:" + uname);
                        System.out.println("元寶數:" + uMoney);
                        dealPet(uname, uid);
                    }
                } else {
                    System.out.println("登錄失敗,賬戶與密碼不匹配");
                    login();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (InputMismatchException e) {
            System.out.println("輸入有誤");
            login();
        }

        return false;
    }

    /**
     * 選擇買寵物或者賣寵物的方法
     */
    public void dealPet(String ownerName, int uid) {

        System.out.println("您可以購買和賣出寵物,購買寵物請輸入1,賣出寵物請輸入2\n1.購買寵物\n2.賣出寵物\n3.回傳上一級\n4.退出系統");
        try {
            Scanner input2 = new Scanner(System.in);
            int choise2 = input2.nextInt();
            if (choise2 < 1 || choise2 > 4) {
                System.out.println("輸入有誤");
                dealPet(ownerName, uid);
            } else {
                switch (choise2) {
                    case 1:
                        //購買寵物
                        buyPet(ownerName, uid);
                        break;
                    case 2:
                        //出售寵物
                        showSellPet(ownerName, uid);
                        break;
                    case 3:
                        //回傳上一級
                        login();
                        break;
                    case 4:
                        System.out.println("--------謝謝使用------");
                        System.exit(0);
                    default:
                        break;
                }
            }
        } catch (InputMismatchException e) {
            System.out.println("輸入有誤");
            dealPet(ownerName, uid);
        }
    }

    /**
     * 顯示主人擁有的寵物
     */
    public void showSellPet(String ownerName, int uid) {
        conn = getConnection();
        String sql25 = "select id,pet_name,pet_price,pet_role_type,pet_type from pet where owner_type = 1 and owner_id =" + uid;
        try {
            state = conn.prepareStatement(sql25);
            rs = state.executeQuery();
            System.out.println("以下是你擁有的寵物:");
//			//如果結果集為空,即該主人沒有寵物,就回傳上一級進行選擇
//			if(!rs.next()){
//				System.out.println("您沒有寵物,將自動回傳上一級");
//				buyPet(ownerName, uid);
//			}
            int num = 1;
            while (rs.next()) {
                int petid = rs.getInt("id");
                String petName = rs.getString("pet_name");
                String petPrice = rs.getString("pet_price");
                System.out.println("這是" + num + "只寵物,編號是" + petid + ",名字叫:" + petName + ",需要" + petPrice + "個元寶");
                num++;
            }
            System.out.println("**************************************");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeObject1();
        sellPet(ownerName, uid);
    }

    public void sellPet(String ownerName, int uid) {
        System.out.println("請輸入你想賣出的寵物編號:");
        try {
            Scanner input27 = new Scanner(System.in);
            int choisePetId = input27.nextInt();
            //先查詢下有哪些商店
            String queryStore = "select owner_id,owner_name from pet_owner where owner_type = 2";
            Connection queryStoreConn = getConnection();
            try {
                state = queryStoreConn.prepareStatement(queryStore);
                rs = state.executeQuery();
                int num = 1;
                if (rs.next()) {
                    //說明有商店存在
                    System.out.println("請輸入你要賣給的商店編號");
                    int storeId1 = rs.getInt("owner_id");
                    String storeName = rs.getString("owner_name");
                    System.out.println(num + "." + storeName+"編號\t:"+storeId1);
                    num++;
                    while (rs.next()) {
                        int storeId = rs.getInt("owner_id");
                        String storeName2 = rs.getString("owner_name");
                        System.out.println(num + "." + storeName2+"\t編號:"+storeId);
                        num++;
                    }
                    System.out.println("8888.回傳上一級\n9999.退出系統");
                    int storeId = input27.nextInt();
                    if (storeId == 8888) {
                        dealPet(ownerName, uid);
                    } else if (storeId == 9999) {
                        System.out.println("-------謝謝使用-------");
                        System.exit(0);
                    }
                    String sql30 = "select pet_name,pet_price,pet_role_type,pet_type from pet where owner_type = 1 and owner_id = "+uid+" and id = "+choisePetId;
                    Connection conn6 = getConnection();
                    try {
                        state = conn6.prepareStatement(sql30);
                        rs = state.executeQuery();
                        if (rs.next()) {
                            String petPrice = rs.getString("pet_price");//寵物價格
                            Connection conn9 = getConnection();
                            conn9.setAutoCommit(false);
                            //修改寵物資訊
                            String sql40 = "update pet set owner_type= 2,owner_id=" + storeId + " where id=" + choisePetId;
                            state = conn9.prepareStatement(sql40);
                            int result20 = state.executeUpdate();
                            //賣主加錢
                            String sql41 = "update pet_owner set money = money +" + petPrice + " where owner_type = 1 and owner_id =" +uid;
                            state = conn9.prepareStatement(sql41);
                            int result21 = state.executeUpdate();
                            //商店扣錢
                            String sql42 = "update pet_owner set money = money -" + petPrice + " where owner_type = 2 and owner_id =" + storeId;
                            state = conn9.prepareStatement(sql42);
                            int result22 = state.executeUpdate();
                            //獲得當前時間
                            Long time1 = System.currentTimeMillis();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String dealTime = sdf.format(time1);
                            //將該條交易添加至交易賬單中
                            String sql43 = "insert into account_info (account_type,pet_id,sale_owner_id,buy_owner_id,price,create_time) VALUES (2," + choisePetId + "," + storeId + "," + uid + "," + petPrice + ",'" + dealTime + "')";
                            state = conn9.prepareStatement(sql43);
                            int result23 = state.executeUpdate();

                            if (result20 > 0 && result21 > 0 && result22 > 0 & result23 > 0) {
                                //提交事務
                                conn9.commit();
                                System.out.println("賣出成功");
                            } else {
                                //回滾事務
                                System.out.println("出售失敗");
                                conn9.rollback();
                            }
                            dealPet(ownerName, uid);
                        } else {
                            System.out.println("沒有該寵物,賣出失敗");
                            dealPet(ownerName, uid);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                        System.out.println("系統例外");
                        dealPet(ownerName, uid);
                    }
                } else {
                    //沒有商店,回傳到上一級
                    dealPet(ownerName, uid);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("資料庫查詢例外!!!");
                dealPet(ownerName, uid);
            }
        } catch (InputMismatchException e) {
            System.out.println("輸入錯誤,請重新輸入");
            sellPet(ownerName, uid);
        }

    }

//	/**
//	 * 顯示新培育寵物并且購買
//	 */
//	public void showNewPet() {
//		// TODO Auto-generated method stub
//
//	}

    /**
     * 寵物商店登錄的方法
     *
     * @return
     */
    public boolean petStoreLogin() {
        boolean flag = false;
        try {
            Scanner input = new Scanner(System.in);
            System.out.println("請先登錄,請您先輸入寵物商店的名字");
            String name = input.next();
            System.out.println("請您輸入寵物商店的密碼:");
            String password = input.next();
            conn = getConnection();
            String sq110 = "select owner_id,owner_name,money from pet_owner where owner_type = 2 and owner_name=? and password=?";
            state = conn.prepareStatement(sq110);
            rs = search(sq110, name, password);
            if (rs.next()) {
                String storeId = rs.getString("owner_id");
                System.out.println("登錄成功");
                PetStoreMake(name,storeId);
            } else {
                System.out.println("登錄失敗");
                login();
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

        return false;
    }

    /*
     * 寵物商店培育新寵物
     */
    public void PetStoreMake(String storeName,String storeId) throws SQLException {
        System.out.println("請輸入數字進行選擇:\n1.查詢店內寵物\n2.培育新寵物\n3.退出登錄\n4.退出系統");
        try {
            Scanner input = new Scanner(System.in);
            int choise7 = input.nextInt();
            if (choise7 < 1 || choise7 > 3) {
                System.out.println("輸入有誤");
                PetStoreMake(storeName,storeId);
            } else {
                switch (choise7) {
                    case 1:
                        storePetQuery(storeName,storeId);
                        break;
                    case 2:
                        storeAddPet(storeName,storeId);
                        break;
                    case 3:
                        //退出登錄,回傳上一級
                        login();
                        break;
                    case 4:
                        System.out.println("-------謝謝使用-------");
                        System.exit(0);
                    default:
                        break;
                }
            }
        } catch (InputMismatchException e) {
            System.out.println("輸入有誤");
            PetStoreMake(storeName,storeId);
        }
    }

    /**
     * 寵物商店培育新寵物的方法
     *
     * @param storeName
     * @throws SQLException
     */
    public void storeAddPet(String storeName,String storeId) throws SQLException {
        System.out.println("請輸入你想添加的寵物的品種名稱(例如:金漸層):");
        Scanner input = new Scanner(System.in);
        String typename = input.next();
        System.out.println("請輸入該寵物的名字:");
        String petName = input.next();
        System.out.println("請輸入該寵物的型別:\n1.普通寵物\n2.新型寵物");
        int animalType = input.nextInt();
        System.out.println("請輸入該寵物的價格:");
        int price = input.nextInt();
        try {
            Connection conn9 = getConnection();
            String sql13 = "insert into pet(pet_name,owner_id,owner_type,pet_price,pet_role_type,pet_type) values ('"+petName+"',"+storeId+",2,"+price+",'"+animalType+"','"+typename+"')";
            state = conn9.prepareStatement(sql13);
            int a = state.executeUpdate();
            if (a > 0) {
                System.out.println("培育新寵物成功");
                PetStoreMake(storeName,storeId);
            } else {
                System.out.println("培育新寵物失敗");
                PetStoreMake(storeName,storeId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 在商店登錄之后進行對店內的寵物進行查詢
     *
     * @param storeName
     */
    public void storePetQuery(String storeName,String storeId) {
        System.out.println("正在查詢店內寵物,,,");
        conn = getConnection();
        String sql11 = "select id,pet_name,pet_price,pet_role_type,pet_type from pet where owner_type = 2 and owner_id = " + storeId;
        try {
            state = conn.prepareStatement(sql11);
            rs = state.executeQuery();
            int i = 1;
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("pet_name");
                String typename = rs.getString("pet_type");
                String petPrice = rs.getString("pet_price");
                System.out.println("第" + i + "只寵物編號是:"+id+",名字:" + name + ",寵物型別:" + typename + ",價格:" + petPrice);
                i++;
            }
            System.out.println("----------------------------");
            PetStoreMake(storeName,storeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 購買寵物的方法
     */
    public void buyPet(String ownerName, int uid) {
        System.out.println("請輸入選擇購買范圍,只輸入選擇項的序號");
        System.out.println("1:購買庫存寵物\n2.購買新培育寵物\n3.回傳上一級");
        try {
            Scanner input3 = new Scanner(System.in);
            int choise5 = input3.nextInt();
            if (choise5 < 1 || choise5 > 3) {
                System.out.println("輸入有誤");
                buyPet(ownerName, uid);
            } else {
                switch (choise5) {
                    case 1:
                        showPetAll(ownerName, uid, 2);
                        break;
                    case 2:
                        buyNewPet(ownerName, uid, 2);
                        break;
                    case 3:
                        //回傳上一級
                        dealPet(ownerName, uid);
                        break;

                    default:
                        break;
                }
            }


        } catch (InputMismatchException e) {
            System.out.println("輸入有誤");
            buyPet(ownerName, uid);

        }
    }

    public void buyNewPet(String ownerName, int uid, int petRoleType) {
        //用于判斷查詢是否有結果
        boolean havePet = false;

        System.out.println("正在幫你查詢新寵物,,,,,");
        conn = getConnection();
        String sql31 = "SELECT id,pet_name,pet_price from pet where pet_role_type= 2 and owner_type = 2";
        try {
            state = conn.prepareStatement(sql31);
            rs = state.executeQuery();
            while (rs.next()) {
                int petid = rs.getInt("id");
                String petName = rs.getString("pet_name");
                String petPrice = rs.getString("pet_price");
                System.out.println("序號為:" + petid + ",名字為:" + petName + ",需要" + petPrice + "個元寶");
                havePet = true;
            }
            if (havePet) {
                System.out.println("請輸入你要購買的新寵物的序號:");
                try {
//					boolean havePet2=false;
                    Scanner input28 = new Scanner(System.in);
                    int newPetId = input28.nextInt();
                    Connection conn7 = getConnection();
                    String sql32 = "SELECT id,pet_name,pet_price,pet_role_type,owner_id from pet where owner_type = 2 and id = " + newPetId;
                    state = conn7.prepareStatement(sql32);
                    rs = state.executeQuery();
                    if (rs.next()) {
                        int storeid = rs.getInt("owner_id");
                        int petPrice = rs.getInt("pet_price");
                        Connection conn8 = getConnection();
                        conn8.setAutoCommit(false);

                        //修改寵物所屬資訊
                        String sql33 = "update pet set owner_type= 1,owner_id=" + uid + " where id=" + newPetId;
                        //修改買主賬戶金額
                        String sql34 = "update pet_owner set money=money-" + petPrice + " where owner_type = 1 and owner_id =" + uid;
                        //修改商店金額
                        String sql35 = "update pet_owner set money=money+" + petPrice + " where owner_type = 2 and owner_id =" + storeid;

                        //獲得當前時間
                        Long time1 = System.currentTimeMillis();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String dealTime = sdf.format(time1);
                        //將該條交易添加至交易賬單中
                        String sql36 = "insert into account_info (account_type,pet_id,sale_owner_id,buy_owner_id,price,create_time) VALUES (2," + newPetId + "," + storeid + "," + uid + "," + petPrice + ",'" + dealTime + "')";

                        state = conn8.prepareStatement(sql33);
                        int result13 = state.executeUpdate();
                        state = conn8.prepareStatement(sql34);
                        int result14 = state.executeUpdate();
                        state = conn8.prepareStatement(sql35);
                        int result15 = state.executeUpdate();
                        state = conn8.prepareStatement(sql36);
                        int result16 = state.executeUpdate();
                        if (result13 > 0 && result14 > 0 && result15 > 0 && result16 > 0) {
                            //如果都成功執行,改變資料,那就提交事務
                            conn8.commit();
                            System.out.println("購買成功");
                        } else {
                            //如果中加你有一條沒有執行成功那就回滾事務
                            System.out.println("購買失敗");
                            conn8.rollback();
                        }
                        buyPet(ownerName, uid);
                    } else {
                        System.out.println("輸入錯誤,沒有該序號的新寵物");
                        buyNewPet(ownerName, uid, 2);
                    }
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("暫時還沒新寵物");
                buyPet(ownerName, uid);
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
    }

    /**
     * 展示庫存寵物名字,序號,型別的方法
     */
    public void showPetAll(String ownerName, int uid, int petRoleType) {
        System.out.println("---------以下是庫存寵物--------");
        conn = getConnection();
        String sql6 = "SELECT pet.id,pet_name,pet_type,pet_role_type,pet_price,pet.owner_id,pet.owner_type,owner_name from pet,pet_owner where pet.owner_id = pet_owner.owner_id and  pet_role_type = 1 and pet.owner_type = 2";
        try {
            state = conn.prepareStatement(sql6);
            rs = state.executeQuery();
            while (rs.next()) {
                int petId = rs.getInt("pet.id");
                int owner_id = rs.getInt("pet.owner_id");
                String petName = rs.getString("pet_name");
                String storeName = rs.getString("owner_name");
                String petType = rs.getString("pet_type");
                String money = rs.getString("pet_price");
                System.out.println("序號:" + petId + ",我的名字叫:" + petName + ",我的品種是:" + petType + ",要購買我要花:" + money + "個元寶!我屬于:" + storeName);
            }
            System.out.println("請輸入你想購買的寵物編號:");
            try {
                Scanner input17 = new Scanner(System.in);
                int choise6 = input17.nextInt();
                //對在商店里的寵物進行ID查詢,符合的就購買
                conn = getConnection();
                String sql15 = "select id,pet_name,pet_price,pet_role_type,pet_type,owner_id from pet where id =" + choise6;
                try {
                    state = conn.prepareStatement(sql15);
                    rs = state.executeQuery();
                    if (rs.next()) {
                        //這里是寵物主人購買寵物的代碼,將寵物的store_ID設定為null,將寵物的owner_ID設定為購買主人的ID
                        //然后主人賬戶減錢,商店的結余加錢,將該條交易添加至交易賬單中
                        int store_id = rs.getInt("owner_id");//這里是選擇的寵物所屬商店的ID
                        int petPrice = rs.getInt("pet_price");//寵物價格
                        //這里用創建一個新的連接
                        Connection conn1 = getConnection();
                        //開啟事務
                        conn1.setAutoCommit(false);
                        //將寵物的主人型別改為個人- 1,將寵物的主人id設定為購買主人的ID
                        String sql18 = "update pet set owner_type=1,owner_id=" + uid + " where pet.id=" + choise6;
                        //寵物主人減錢
                        String sql19 = "update pet_owner set money = money -" + petPrice + " where owner_type = 1 and owner_id=" + uid;
                        //寵物商店加錢
                        String sql20 = "update pet_owner set money = money +" + petPrice + " where owner_type = 2 and owner_id=" + store_id;
                        //獲得當前時間
                        Long time1 = System.currentTimeMillis();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dealTime = sdf.format(time1);
                        //將該條交易添加至交易賬單中
                        String sql21 = "insert into account_info (account_type,pet_id,sale_owner_id,buy_owner_id,price,create_time) VALUES (1," + choise6 + "," + store_id + "," + uid + "," + petPrice + ",'" + dealTime + "')";

                        state = conn1.prepareStatement(sql18);
                        int result2 = state.executeUpdate();
                        state = conn1.prepareStatement(sql19);
                        int result3 = state.executeUpdate();
                        state = conn1.prepareStatement(sql20);
                        int result4 = state.executeUpdate();
                        state = conn1.prepareStatement(sql21);
                        int result5 = state.executeUpdate();
                        if (result2 > 0 && result3 > 0 && result4 > 0 && result5 > 0) {
                            //如果都成功執行,改變資料,那就提交事務
                            conn1.commit();
                            System.out.println("購買成功");
                        } else {
                            //如果中加你有一條沒有執行成功那就回滾事務
                            System.out.println("購買失敗");
                            conn1.rollback();
                        }

                        //回傳上一級
                        buyPet(ownerName, uid);
                    } else {
                        System.out.println("購買失敗");
                        //回傳上一級
                        buyPet(ownerName, uid);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } catch (InputMismatchException e) {
                System.out.println("輸入有誤");
                showPetAll(ownerName, uid, 1);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

}

操作資料庫的工具類BaseDAO:

package com.dao;

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

/**
 * @author 咕嚕科
 * ClassName: BaseDao
 * date: 2021/8/26 22:11
 * Description:
 * version 1.0
 */

public class BaseDAO {

    public Connection conn = null;
    public PreparedStatement state = null;
    public ResultSet rs = null;


    /**
     * 獲取連接物件
     * @return
     */
    public Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pet_store", "root", "123");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    public int update(String sql, Object...obs) throws SQLException {
        int result = 0;
        conn = getConnection();
        state = conn.prepareStatement(sql);

        for (int i = 0; i < obs.length; i++) {
            state.setObject(i + 1, obs[i]);
        }
        result = state.executeUpdate();
        return result;
    }

    public ResultSet search(String sql, Object...obs) {
        try {
            conn = getConnection();
            state = conn.prepareStatement(sql);
            for (int i = 0; i < obs.length; i++) {
                state.setObject(i + 1, obs[i]);
            }
            rs = state.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }
    public void closeObject1() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (state != null) {
                state.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void closeObject2(AutoCloseable... obs) {
        try {
            for (int i = 0; i < obs.length; i++) {
                if (obs[i] != null) {
                    obs[i].close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Main方法入口:

public class MainTest {

    public static void main(String[] args) {
        System.out.println("=========寵物商店啟動=======");
        PetManage pm = new PetManage();
        //顯示所有寵物
        pm.showAll();
    }

}

需要將jar包匯入,才能正常運行
在這里插入圖片描述
資料庫表
寵物表(pet)

/*
Navicat MySQL Data Transfer

Source Server         : hth
Source Server Version : 50562
Source Host           : localhost:3306
Source Database       : pet_store

Target Server Type    : MYSQL
Target Server Version : 50562
File Encoding         : 65001

Date: 2021-11-07 20:28:33
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `pet`
-- ----------------------------
DROP TABLE IF EXISTS `pet`;
CREATE TABLE `pet` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pet_name` varchar(20) NOT NULL,
  `pet_price` decimal(10,2) NOT NULL,
  `pet_role_type` int(3) NOT NULL DEFAULT '1' COMMENT '寵物型別:1-普通寵物;2-培育寵物',
  `pet_type` varchar(20) NOT NULL COMMENT '寵物品種',
  `owner_id` int(5) NOT NULL,
  `owner_type` int(5) NOT NULL COMMENT '主人型別:1-個人;2-商店',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of pet
-- ----------------------------
INSERT INTO `pet` VALUES ('1', '歡歡', '5.00', '1', '哈士奇', '1', '1');
INSERT INTO `pet` VALUES ('2', '齊齊', '10.00', '1', '藏獒', '4', '2');
INSERT INTO `pet` VALUES ('3', '露露', '20.00', '1', '銀漸層', '3', '1');
INSERT INTO `pet` VALUES ('4', '布布1', '5.00', '1', '金毛', '3', '1');
INSERT INTO `pet` VALUES ('5', '布布2', '5.00', '1', '哈士奇', '4', '2');
INSERT INTO `pet` VALUES ('6', '布布3', '5.00', '1', '銀漸層', '5', '2');
INSERT INTO `pet` VALUES ('7', '布布4', '5.00', '1', '金毛', '4', '2');
INSERT INTO `pet` VALUES ('8', '布布5', '5.00', '1', '銀漸層', '5', '2');
INSERT INTO `pet` VALUES ('9', '布布6', '5.00', '1', '哈士奇', '4', '2');
INSERT INTO `pet` VALUES ('10', '布布7', '5.00', '1', '金毛', '5', '2');
INSERT INTO `pet` VALUES ('11', '龍龍1', '30.00', '2', '哈士奇', '3', '1');
INSERT INTO `pet` VALUES ('12', '龍龍2', '40.00', '2', '銀漸層', '5', '2');
INSERT INTO `pet` VALUES ('13', '龍龍3', '50.00', '2', '藏獒', '4', '2');
INSERT INTO `pet` VALUES ('14', '小輝2', '50.00', '2', '金漸層', '4', '2');
INSERT INTO `pet` VALUES ('15', '小輝3', '50.00', '2', '金漸層', '4', '2');
INSERT INTO `pet` VALUES ('16', '小輝4', '50.00', '2', '金漸層', '4', '2');
INSERT INTO `pet` VALUES ('17', '小哈', '50.00', '2', '金漸層', '5', '2');
INSERT INTO `pet` VALUES ('18', '小哈', '5.00', '1', '金漸層', '5', '2');

用戶-商店資訊表(pet_owner)

/*
Navicat MySQL Data Transfer

Source Server         : hth
Source Server Version : 50562
Source Host           : localhost:3306
Source Database       : pet_store

Target Server Type    : MYSQL
Target Server Version : 50562
File Encoding         : 65001

Date: 2021-11-07 20:28:44
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `pet_owner`
-- ----------------------------
DROP TABLE IF EXISTS `pet_owner`;
CREATE TABLE `pet_owner` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` int(11) NOT NULL,
  `owner_name` varchar(20) NOT NULL COMMENT '寵物擁有者名稱',
  `owner_type` int(11) NOT NULL DEFAULT '1' COMMENT '主人型別:1-個人;2-商店',
  `money` decimal(11,0) NOT NULL DEFAULT '0' COMMENT '金幣',
  `address` varchar(30) DEFAULT NULL,
  `password` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of pet_owner
-- ----------------------------
INSERT INTO `pet_owner` VALUES ('10', '3', 'hth', '1', '9825', '江西', '123');
INSERT INTO `pet_owner` VALUES ('12', '2', '韋德', '1', '14710', '湖北', '123');
INSERT INTO `pet_owner` VALUES ('13', '1', 'kobe', '1', '5000', '山東', '123');
INSERT INTO `pet_owner` VALUES ('14', '4', '重慶觀音橋', '2', '332240', '重慶', '123');
INSERT INTO `pet_owner` VALUES ('15', '5', '西苑', '2', '134625', '深圳', '123');

交易資訊表(account_info)

/*
Navicat MySQL Data Transfer

Source Server         : hth
Source Server Version : 50562
Source Host           : localhost:3306
Source Database       : pet_store

Target Server Type    : MYSQL
Target Server Version : 50562
File Encoding         : 65001

Date: 2021-11-07 20:28:39
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `account_info`
-- ----------------------------
DROP TABLE IF EXISTS `account_info`;
CREATE TABLE `account_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_type` varchar(255) DEFAULT NULL,
  `buy_owner_id` int(11) NOT NULL,
  `buy_owner_name` varchar(30) DEFAULT NULL,
  `buy_owner_type` int(11) DEFAULT NULL,
  `sale_owner_id` int(11) NOT NULL,
  `sale_owner_type` int(11) DEFAULT NULL,
  `sale_owner_name` varchar(30) DEFAULT NULL,
  `pet_id` int(11) NOT NULL,
  `price` decimal(10,0) DEFAULT NULL,
  `create_time` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of account_info
-- ----------------------------
INSERT INTO `account_info` VALUES ('8', '1', '3', null, null, '4', null, null, '2', '5', '2021-11-07 17:51:38');
INSERT INTO `account_info` VALUES ('9', '1', '3', null, null, '5', null, null, '4', '5', '2021-11-07 17:52:23');
INSERT INTO `account_info` VALUES ('10', '2', '3', null, null, '5', null, null, '3', '20', '2021-11-07');
INSERT INTO `account_info` VALUES ('11', '2', '3', null, null, '4', null, null, '11', '30', '2021-11-07');
INSERT INTO `account_info` VALUES ('12', '2', '3', null, null, '5', null, null, '12', '40', '2021-11-07');
INSERT INTO `account_info` VALUES ('13', '2', '3', null, null, '4', null, null, '13', '50', '2021-11-07');
INSERT INTO `account_info` VALUES ('16', '2', '3', null, null, '4', null, null, '2', '10', '2021-11-07');
INSERT INTO `account_info` VALUES ('17', '1', '3', null, null, '4', null, null, '2', '10', '2021-11-07 20:14:25');
INSERT INTO `account_info` VALUES ('18', '2', '3', null, null, '4', null, null, '11', '30', '2021-11-07');
INSERT INTO `account_info` VALUES ('19', '2', '3', null, null, '4', null, null, '2', '10', '2021-11-07');

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/352190.html

標籤:其他

上一篇:windows螢屏錄制實作方法

下一篇:AUTOSAR開發工具DaVinci Configurator里的Modules

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more