-2

I want to insert multiple records simultaneously in a table from various threads whith this code. But only half of threads works, for the rest shows: Error: Duplicate entry ' ' for key 'PRIMARY'

 final Connection con=MyConnection.connect();
         try{
            con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            con.setAutoCommit(false);
         }catch (Exception e) { System.out.println("Error: " + e.getMessage()); }
            Thread[] threads = new Thread[50];
             for (int i = 0; i < threads.length; i++) {
                 threads[i] = new Thread(new Runnable() {
                     public void run() {
                            try{
                                int idr=0; 
                                    Statement st = con.createStatement();
                                    ResultSet rs1 = st.executeQuery("SELECT max(id) FROM employee;");
                                    rs1.next();
                                    idr = rs1.getInt(1)+1;
                                   st.executeUpdate("insert into employee(id,name,address) values('"+idr+"','"+ name+"','"+adrress+"');");
                                   con.commit(); 
                            } catch (Exception e) { System.out.println("Error: " + e.getMessage()); }
                          }
                 });
                 threads[i].start();
             }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Peggy
  • 49
  • 5
  • What is your question? The error-message is pretty self-explanatory. – Patrik Jul 06 '15 at 12:17
  • It looks like you'll need to handle duplicate keys when inserting you data. Maybe a look at [this question](http://stackoverflow.com/q/548541/448591) helps. – Jakob Runge Jul 06 '15 at 12:19
  • "Duplicate keys" sounds like an oxymoron. If it's not unique, it's not a key. – duffymo Jul 06 '15 at 12:27

1 Answers1

1

You don't need to get the max ID from your table for every insert. Every database has an option to handle it automatically. You need to have your Primary Key 'Auto Incremented'. This way, ID for every insert will be automatically incremented by the database. Just run the following query once.

ALTER TABLE EMPLOYEE MODIFY COLUMN ID INT AUTO_INCREMENT PRIMARY KEY;

Once you are done updating your table. Just remove the ID part from your insert query. You don't need to write in your query as it will be handled by the Database. Hope that helps!

ssadaqat
  • 158
  • 6