首页 > 解决方案 > Java 结果集不适用于预先编写好的 SQL

问题描述

我的 Java 程序不会显示或使用在 Eclipse 中使用之前已放入表中的 SQL 值。

我的意思是我可以向表中添加值,它会告诉我是否再次添加相同的值,但是当我尝试使用我输入的表中已经存在的值时它会锁定SQL。

我不知所措,我不明白为什么会这样。我只需要它告诉我已经存在的值存在该值。这是我的代码:

public void addCourse(Statement st){   //**********This function adds a course to the database.
        String courseCode, courseTitle;
        int entriesChanged;   


        try {
            System.out.println("Please enter a course code you would like to add: ");
            courseCode = scan.next().toUpperCase();
            ResultSet rs = st.executeQuery("select * from Course where code = '" + courseCode + "'");

            if (rs.next()) {
                System.out.println("This course code already exists, please 
try again.");
            } else {
                System.out.println("Please enter the title for the course: ");
                courseTitle = scan.next().toUpperCase();
                entriesChanged = st.executeUpdate("Insert into Course values 
('" + courseCode + "','" + courseTitle + "')");
                System.out.println("You just added " + entriesChanged + " 
entries to the course list.");
            }
            rs.close();  //**********Closed the result set in this function.
        } catch (SQLException e) {
            System.out.println("There was an error during runtime, Error: " + 
e.getMessage());
        }

这是我通过 Driver.java 类共享的连接语句:

try (Connection conn 

=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", Chicken1") //connect oracle
                ) { 
Statement st = conn.createStatement();

当我说“它锁定”时,我的意思是一旦你输入预先编写的 SQL 表中已经存在的课程代码,它就会要求用户输入课程的标题,然后它只是让你无休止地输入控制台而不继续程序。

但是,如果我添加了预先编写的表格中不存在的课程,那么它会将其添加到数据库中,并且不会让我重新输入我已经输入的课程代码。

但是,当试图让程序阻止我输入预先编写的 SQL 表上存在的课程代码时,就是它“锁定”的时候。

标签: javasqlsetresultset

解决方案


推荐阅读