如何针对我的情况在JDBC中正确使用ResultSet类?

时间:2018-08-16 22:51:35

标签: java mysql jdbc

我将客户添加到数据库中,但前提是数据库中没有与我刚输入的客户ID相同的其他客户ID。我正在使用JDBC和MySQL在Eclipse中执行此操作。有人可以告诉我是否正确设置了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();
            }
        }

1 个答案:

答案 0 :(得分:0)

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