0

我正在尝试开发一个程序,您想在其中添加一本新书(标题、作者、日期……),但我不想多次添加作者。我希望程序检查作者是否已经存在在表中,如果没有,它将添加他...这是我的代码:

public void insert_bk(String m, String a, String b, String c, String d, String e) {
    String sql="Select * from author where Full_Name='"+b+"'";
    System.out.println(sql);

    try {  
        opencn();
        Statement st=cn.createStatement();
        ResultSet rs=st.executeQuery(sql);

        while (rs.next()) { 
            String id=rs.getString("Author_ID");
            System.out.println(id);
            st.executeUpdate("INSERT into book (`Book_ID`,`Title`,`Author_ID`,`Date_of_release`,`Theme`,`Edition`)"+ "VALUES ('" + m+ "','" + a+ "','" + id+ "', '" + d+ "', '" + e+ "', '" + c+ "')");
        }  
    }
    catch(SQLException exp) {
        System.out.println(exp.getMessage());
    }
}

在这段代码中,它只是检查作者是否存在并添加这本书......我怎样才能做出这样的条件,即如果作者不存在,它将把他和这本书一起添加?

有任何想法吗?先感谢您 :)

4

4 回答 4

1

您应该将 rs.next() 放入 if 语句中,而不是使用 while 循环。如果调用返回 false,则没有作者存在并且必须插入。

于 2013-05-05T19:38:17.553 回答
0

您可以通过在语句中添加关键字 IGNORE 来进行条件插入。根据您使用的 SQL 数据库,答案会略有不同。我将在这里演示 MySQL 和 sqlite 的两种方式,但当然还有更多。

对于 MySQL

INSERT IGNORE INTO authors VALUES(?,?...,?) 

对于 SQLite

INSERT OR IGNORE INTO authors VALUES(?,?,...,?);
于 2013-05-05T19:33:38.870 回答
0

你可以做这个存储过程

declare @i int
Select @i=count(*) from author where Full_Name=@FullName
IF(@i < 1)
  BEGIN
  // INSERT 
  END
于 2013-05-05T19:41:21.863 回答
0

这可能会有所帮助

String query = "Select * from author where Full_Name='"+b+"'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr;
con.Open();
cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();

if (rdr.Read()) { // if you have an author
    //do your updation code here
}
else {
    //if rdr.Read() gives 0 which will be the case when our
    //author wont exist past the code for adding an author here
}
于 2013-05-05T19:43:08.000 回答