-1

I am new to write sql using java. I can create the tables like this:

String queryCreateBookTable = "create table Book (" + 
    "isbn char(13) not null," + 
    "author char(30)," + 
    "title char(30)," +
    "subject char(30)," +
    "primary key(isbn))";

And I want to insert some rows from a given array which contains many rows. So I tried this code and it isn't working. How can I fix it without duplicate of primary key and null situation?

public int insertBook(Book[] books)
{
    int result = 0;
    int art=0;
    String query = null;
    String[] depo=null;
    while(books[art].getIsbn().length() == 13 )
    {
        if(art==0)
        {
            depo[0]=books[0].getIsbn();
        }
        for(int i=0;i<art;i++)
        {
            if(books[art].getIsbn() ==depo[i])
                result++;
            else
                result=0;
        }
        if(result==0)
        {
            query= "insert into Book values ('" + 
            books[art].getIsbn()+ "','" + 
            books[art].getAuthor() + "','" + 
            books[art].getTitle() + "','" + 
            books[art].getSubject() +   "')";
        }
    }
}
Termininja
  • 6,620
  • 12
  • 48
  • 49

2 Answers2

1

you want unique ISBNs, so you can:

  • perform the insert, let it fail, catch the SQLException (ignore the duplicate) and keep going (probably expensive)
  • pre-filter the collection. For example use a java.util.Set to remove duplicate ISBNs (brittle approach)
  • check before hand if the ISBN already exists in the db. Basically do a select first and do the insert only if you get an empty ResultSet. (probably best)
user2560528
  • 105
  • 6
0

Your requirement is insert if not exists. You can use insert ignore.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

If primary exists and you want to update if it exists you can use insert on duplicate key update as described in the above link.

For checking null condition, you have to put null checks using if condition and if it is null then skip the current record and continue to the next record

Community
  • 1
  • 1
prem kumar
  • 5,641
  • 3
  • 24
  • 36