为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻阅古今 2021-07-19 16:17:21
我正在将客户添加到数据库中,但前提是数据库中没有其他 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();            }        }
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

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


查看完整回答
反对 回复 2021-07-29
  • 1 回答
  • 0 关注
  • 172 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信