mysql 为什么我的查询只适用于小于10的数字?

syqv5f0l  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(255)

我在输入数据时使用了这个函数。所以我需要检查db中是否有一个具有这个id的雇员。我在注册时使用的函数和这个方法是一样的。但是当涉及到整数时,它只检查它是否小于10(或者它可能是第一个插入的值)。这是我检查id唯一性的代码:

private int checkUnique() {
    try {
        Scanner scan = new Scanner(System.in);
        id = scan.nextInt();
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:...", "...", "...");
        Statement st = connection.createStatement();
        ResultSet res = st.executeQuery("select id_emp from employees");
        while (res.next()) {
            if (res.getInt("id_emp")==getId()) {
                res.close();
                st.close();
                connection.close();
                System.out.println("There is employee with this id");
                System.out.println("Enter id");
                checkUnique();
            } else {
                res.close();
                st.close();
                connection.close();
                return id;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

这就是我在代码中使用它的方式:

Statement st = connection.createStatement();
String sql = "INSERT INTO employees (id_emp, first_name, last_name, cnt_kids, cnt_dkids,is_single,added_by) " +
        "VALUES (?, ?, ?, ?, ?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
System.out.println("Enter id");
id = checkUnique();

这有什么不对?
例如,当id=2时,这段代码要求输入其他id(它确实在表中),但当我插入id=12时(也在表中),它就跳过了。

CREATE TABLE `employees` (
  `id_emp` int NOT NULL,
  `first_name` varchar(30) DEFAULT NULL,
  `last_name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
  `cnt_kids` int DEFAULT NULL,
  `cnt_dkids` int DEFAULT NULL,
  `is_single` bit(1) DEFAULT NULL,
  `added_by` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
  PRIMARY KEY (`id_emp`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
cbeh67ev

cbeh67ev1#

使用预准备语句
下面是一些示例代码:

public class SQLMain {
    public static void main(String[] args) throws SQLException {
        System.out.println("ID to check:");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test");
        PreparedStatement preparedStatement = connection.prepareStatement("select id_emp from employees where id_emp = ?");
        preparedStatement.setInt(1, id);
        
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()) {
            // we have a row
            System.out.println("Found employee with id of: " + resultSet.getInt(1));
        } else {
            // no row found - therefore unique 
            System.out.println("not found");
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        scanner.close();
    }
}

相关问题