如果作者不存在,java将其插入表中,但始终返回其ID
我试图让这个函数只在数据库中不存在作者时插入作者
如果作者已经在“authors”表中(意思是相同的名字和姓氏),那么我希望此函数不插入作者,但我仍然希望它返回作者的ID,我不确定如何执行此操作
下面是我的insertAuthor函数,它可以插入作者,即使他已经存在:
public static int insertAuthor(Connection conn, Author author) throws SQLException
{
ResultSet keys = null;
int authorId;
// Insert the new Authors into the authors table
String sqlInsertAuthor = "INSERT into authors"
+ "(author_firstname, author_lastname)"
+ " VALUES (?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sqlInsertAuthor, Statement.RETURN_GENERATED_KEYS);)
{
statement.setString(1, author.getFirstName());
statement.setString(2, author.getLastName());
// Execute and return number of rows affected
int affectedRows = statement.executeUpdate();
// The number of affected rows should be equal to 1
if (affectedRows == 1)
{
keys = statement.getGeneratedKeys();
keys.next();
authorId = keys.getInt(1);
}
else
{
return 0;
}
}
catch (SQLException e)
{
System.err.println("ERROR INSERTING AUTHOR: " + e.getMessage());
return 0;
}
return authorId;
}
共 (0) 个答案