【问题标题】:Trying to find if an item exists in database table, if it doesn' t exist. add it试图查找数据库表中是否存在某个项目,如果它不存在。添加它
【发布时间】:2013-04-29 14:06:41
【问题描述】:

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

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());
    }
}

在此代码中,它只是检查作者是否存在并添加书籍...我如何设置如果作者不存在则将他与书籍一起添加的条件?

有什么想法吗? 提前谢谢你:)

【问题讨论】:

  • 就像你添加我要说的书一样。

标签: java sql database select


【解决方案1】:

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

【讨论】:

  • 正如 Linus 所写,您插入作者的方式与插入书籍的方式相同。
【解决方案2】:

你可以做这个存储过程

declare @i int
Select @i=count(*) from author where Full_Name=@FullName
IF(@i < 1)
  BEGIN
  // INSERT 
  END

【讨论】:

    【解决方案3】:

    这可能会有所帮助

    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
    }
    

    【讨论】:

      【解决方案4】:

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

      对于 MySQL

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

      对于 SQLite

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

      【讨论】:

      • 我的插入没有问题...我的条件有问题,如果作者存在则插入书...如果作者不存在...插入作者然后新书...这是我遇到的问题...
      • 所以我编辑了我的答案以反映你想要做什么。修改后的答案显示了如何插入作者,但如果作者已经存在,则会忽略插入。
      猜你喜欢
      • 2020-02-20
      • 2020-09-30
      • 2017-11-09
      • 2018-06-20
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2022-12-11
      相关资源
      最近更新 更多