我正在將客戶添加到數據庫中,但前提是數據庫中沒有其他 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(); } }
添加回答
舉報
0/150
提交
取消