import java.sql.*;

public class PhoneBrandManagement {

public static void main(String[] args) {
    // JDBC连接数据库
    String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    String user = "root";
    String password = "123456";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection(url, user, password);
        System.out.println("数据库连接成功!");
        // 从控制台读取品牌名称、厂商名称和产地
        String brandName = null;
        String manufacturer = null;
        String origin = null;
        while (true) {
            System.out.println("请输入品牌名称:");
            brandName = System.console().readLine();
            if (brandName.trim().length() == 0) {
                System.out.println("品牌名称不能为空!");
            } else {
                break;
            }
        }
        while (true) {
            System.out.println("请输入厂商名称:");
            manufacturer = System.console().readLine();
            if (manufacturer.trim().length() == 0) {
                System.out.println("厂商名称不能为空!");
            } else {
                break;
            }
        }
        while (true) {
            System.out.println("请输入产地:");
            origin = System.console().readLine();
            if (origin.trim().length() == 0) {
                System.out.println("产地不能为空!");
            } else {
                break;
            }
        }
        // 判断数据库中是否已经存在该品牌
        String sql = "SELECT * FROM phone_brand WHERE brand_name=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, brandName);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            System.out.println("该品牌已经存在于数据库中!");
        } else {
            // 添加品牌到数据库中
            sql = "INSERT INTO phone_brand(brand_name,manufacturer,origin) VALUES(?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, brandName);
            pstmt.setString(2, manufacturer);
            pstmt.setString(3, origin);
            int count = pstmt.executeUpdate();
            if (count > 0) {
                System.out.println("品牌添加成功!");
            } else {
                System.out.println("品牌添加失败!");
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        // 关闭数据库连接
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

原文地址: https://www.cveoy.top/t/topic/dbf7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录