如何正确使用jdbc中的resultset类来解决我的问题?

enyaitl3  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(215)

我正在将客户添加到数据库中,但前提是数据库中没有其他与我刚才输入的customerid相同的customerid。我在eclipse中使用jdbc和mysql来实现这一点。有人能告诉我,如果我的while循环设置正确,以实现这一点吗?我得到了很多奇怪的结果,所以可能不是。我已经在网上找了好几个小时了,但我没法让它工作。如何正确地执行此操作?下面是我的一段代码。

public void addCust() {
    String url = "jdbc:mysql://localhost:3306/northwind?useSSL=false&serverTimezone=EST";
    String username = "root";
    String password = "<password>";
    String tempCustID, custID, comp, contName, contTitle, addr, city, reg, postCode, country, phone, fax;

    System.out.println("Loading driver...");

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("Driver loaded!");
    }catch (ClassNotFoundException e) {
        throw new IllegalStateException("Cannot find the driver in the classpath!", e);
    }

    System.out.println("Connecting database...");

    try {
        Connection mycon = DriverManager.getConnection(url, username, password);
        System.out.println("Database connected!");

        Scanner keyboard1 = new Scanner(System.in);

        System.out.println("Enter 5 letters to identify the customer as.");
        tempCustID = keyboard1.nextLine();
        custID = tempCustID.toUpperCase();
        /**
        if(custID == "") {
            System.out.println("Must enter a value.");
            addCust();
        }
        */

        PreparedStatement stat = mycon.prepareStatement("SELECT CustomerID FROM customers");
        ResultSet cust = stat.executeQuery();
        while(cust.next()) {
            String customerID = cust.getString("CustomerID");
            if(custID == customerID) {
                System.out.println("Customer ID already exists. Please enter a different sequence of 5 letters to identify the customer as.");
                options();
            }
        }
lf5gs5x2

lf5gs5x21#

使用equals方法比较字符串,而不是“==”

相关问题