我正在尝试将名称、哈希密码、盐和哈希类型插入数据库。唯一改变的是参数的类型。我相信这可以做得更有效。如何避免使用重载?我需要使用泛型吗?谢谢。
插入方法
protected void insert(String name, String secretpassword, String salt, String type)
{
String sql = "INSERT INTO login(username,password,salt,type) VALUES(?,?,?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setString(2, secretpassword);
pstmt.setString(3, salt);
pstmt.setString(4, type);
pstmt.executeUpdate();
System.out.println("Successful");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
protected void insert(String name, byte[] secretpassword, String salt, String type)
{
String sql = "INSERT INTO login(username,password,salt,type) VALUES(?,?,?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setString(2, Arrays.toString(secretpassword));
pstmt.setString(3, salt);
pstmt.setString(4, type);
pstmt.executeUpdate();
System.out.println("Successful");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
最佳答案
您可以从第二个方法调用第一个方法,例如:
protected void insert(String name, byte[] secretpassword, String salt, String type)
{
insert(name, Arrays.toString(secretpassword), salt, type);
}
关于java - 如何避免由于代码重复而导致的过载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54940409/