我在輸入資料時使用這個函式。所以我需要檢查資料庫中是否有具有此 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;
uj5u.com熱心網友回復:
使用準備好的陳述句
這是一些示例代碼:
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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534421.html
標籤:爪哇数据库数据库jdbc
上一篇:為什么我在嘗試與sequelize、mysql和Nodejs實作一對多關系時收到“UnhandledPromiseRejectionWarning:E??rroratQuery.run”?
