简体   繁体   中英

How to Insert an ArrayList into Database

I am creating an arraylist from my derby database like this:

public ArrayList<ArrayList<String>> createArray(String ticket, JLabel message){


String sl = ticket;
List rowData ;
List<String> columnHeaders;
ArrayList<ArrayList<String>> tableData =  null;

try{
conn= new data.connection().db();
String query="SELECT * FROM SERVICE_TICKET WHERE TICKET_NO ='"+sl+"' ";
stmtt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmtt.executeQuery(query);
md = rs.getMetaData();
            int count = md.getColumnCount();
            columnHeaders = new ArrayList<>();
            tableData = new ArrayList<>();
         /*
                for (int i = 1; i <= count; i++) {
                columnHeaders.add(md.getColumnName(i));
                System.out.print(columnHeaders);
            }

         */
            while (rs.next()) {
                rowData = new ArrayList<>();
                for (int i = 2; i <= count; i++) {
                    rowData.add(rs.getObject(i));
                    message.setText(rs.getObject(i).toString());
                }
                tableData.add((ArrayList<String>) rowData);
            }
            System.out.println(tableData);
 }
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Unknown Error!! Data cannot be displayed!"+ex);
} 
finally{try{stmtt.close(); conn.close(); rs.close();} catch(SQLException ex){}}

return tableData;
    }

and trying to insert the data into a remote MySQL Database like this:

public void save(String ticket, JLabel message){

ArrayList<ArrayList<String>> tableData = createArray(ticket, message);


 String query = "INSERT INTO SERVICE_TICKET(ID, TICKET_NO, " // VARCHAR(40),
    +" SL_NO, " //INTEGER,
    +" CODE, " // VARCHAR(30),
    +" ITEM_NAME, " // VARCHAR(300),
    +" GROUP_NAME, " // VARCHAR(50),

    +" QNTY, " // INTEGER,
    +" UNIT, " // VARCHAR(30),
    +" TAXABLE, " //  VARCHAR(3),
    +" BONUSABLE, " //  VARCHAR(3),

    +" PRICE, " // DECIMAL(30 , 2),
    +" AMOUNT, "// DECIMAL(30, 2) DEFAULT 0.00,

    +" DISC_PERCENTAGE, " // DECIMAL(30, 2) DEFAULT 0.00,
    +" DISCOUNT, " // DECIMAL(30, 2) DEFAULT 0.00,

    +" FEDERAL, " //  DECIMAL(30, 2) DEFAULT 0.00,
    +" GST, " // DECIMAL(30, 2) DEFAULT 0.00,
    +" TOTAL_TAX, " // DECIMAL(30, 2) DEFAULT 0.00,

    +" NET_AMOUNT) " // DECIMAL(30 , 2) 
        +" VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ;


 try{
     Class.forName("java.sql.Driver");
     conn = DriverManager.getConnection("jdbc:mysql://www.example.com:3306/myDatabase", "user_1", "password_123");
     conn.setAutoCommit(false);
     stmt = conn.prepareStatement(query);
 if(conn != null ){
 JOptionPane.showMessageDialog(null, "Connected to Internet....");}
 else{JOptionPane.showMessageDialog(null, "Failed to connect to the server");}


     for(int i = 0; i<tableData.size(); i++){ 
     ArrayList<String> innerList = (ArrayList<String>)tableData.get(i);
     for(int j = 0; j<innerList.size(); j++){ 

     stmt.setString(1, innerList.get(j).toString()) ; //   TICKET_NO VARCHAR(40),
     stmt.setInt(2, Integer.parseInt(innerList.get(j).toString())) ; //SL_NO INTEGER,
     stmt.setString(3, innerList.get(j).toString()) ; //CODE VARCHAR(30),
     stmt.setString(4, innerList.get(j).toString()) ; //ITEM_NAME VARCHAR(300),
     stmt.setString(5, innerList.get(j).toString()) ; // GROUP_NAME VARCHAR(50),

     stmt.setInt(6, Integer.parseInt(innerList.get(j).toString())) ; // QNTY INTEGER,
     stmt.setString(7, innerList.get(j).toString()) ; //    UNIT VARCHAR(30),
     stmt.setString(8, innerList.get(j).toString()) ; //    TAXABLE VARCHAR(3),
     stmt.setString(9, innerList.get(j).toString()) ; //    BONUSABLE VARCHAR(3),

     stmt.setDouble(10, Double.parseDouble(innerList.get(j).toString())) ; //   PRICE DECIMAL(30 , 2),
     stmt.setDouble(11, Double.parseDouble(innerList.get(j).toString())) ; //   AMOUNT DECIMAL(30, 2) DEFAULT 0.00,

     stmt.setDouble(12, Double.parseDouble(innerList.get(j).toString())) ; //   DISC_PERCENTAGE DECIMAL(30, 2) DEFAULT 0.00,
     stmt.setDouble(13, Double.parseDouble(innerList.get(j).toString())) ; //   DISCOUNT DECIMAL(30, 2) DEFAULT 0.00,

     stmt.setDouble(14, Double.parseDouble(innerList.get(j).toString())) ; //   FEDERAL DECIMAL(30, 2) DEFAULT 0.00,
     stmt.setDouble(15, Double.parseDouble(innerList.get(j).toString())) ; //   GST DECIMAL(30, 2) DEFAULT 0.00,
     stmt.setDouble(16, Double.parseDouble(innerList.get(j).toString())) ; //   TOTAL_TAX DECIMAL(30, 2) DEFAULT 0.00,

     stmt.setDouble(17, Double.parseDouble(innerList.get(j).toString())) ; //   NET_AMOUNT DECIMAL(30 , 2)

     stmt.addBatch(); 

     stmt.executeBatch();
    conn.commit();

 }}

     JOptionPane.showMessageDialog(null, "Data saved successfully.");
 }
 catch(SQLException | ClassNotFoundException ex){JOptionPane.showMessageDialog(null, "Cannot Save"+ex);}
 finally{
 try{
     stmt.close(); conn.close(); conn.setAutoCommit(true);
 }catch(SQLException ex){}
 }
 }   

The arraylist displays fine in console. But it gives me always NumberFormatException... What is wrong in my code ?

One more Question: Is there any other option, that I can insert my table data from local computer (Running in Derby Database) to a remote MySQL database ? Please help.

This is where you're wrong:

for(int j = 0; j<innerList.size(); j++){ 

stmt.setString(1, innerList.get(j).toString()) ; //   TICKET_NO VARCHAR(40),
stmt.setInt(2, Integer.parseInt(innerList.get(j).toString())) ; //SL_NO INTEGER,

Observe that you're always accessing the same index from the innerList : j . When in fact you probably want something more along the lines of

for (int j = 0; j < innerList.size(); j++) { 
    stmt.setObject(j + 1, innerList.get(j));
}

Besides, Siva Mondi also has a correct observation with executeBatch() and commit() being at the wrong loop level. Intuitively, I'd say there are about 1-2 other problems in that code... As mentioned in the comments, you might indeed be better off with a higher abstraction level, such as JPA , Spring JDBC or jOOQ

Please carefully check these lines again:

 stmt.setDouble(10, Double.parseDouble(innerList.get(j).toString())) ; //   PRICE DECIMAL(30 , 2),
 stmt.setDouble(11, Double.parseDouble(innerList.get(j).toString())) ; //   AMOUNT DECIMAL(30, 2) DEFAULT 0.00,

 stmt.setDouble(12, Double.parseDouble(innerList.get(j).toString())) ; //   DISC_PERCENTAGE DECIMAL(30, 2) DEFAULT 0.00,
 stmt.setDouble(13, Double.parseDouble(innerList.get(j).toString())) ; //   DISCOUNT DECIMAL(30, 2) DEFAULT 0.00,

 stmt.setDouble(14, Double.parseDouble(innerList.get(j).toString())) ; //   FEDERAL DECIMAL(30, 2) DEFAULT 0.00,
 stmt.setDouble(15, Double.parseDouble(innerList.get(j).toString())) ; //   GST DECIMAL(30, 2) DEFAULT 0.00,
 stmt.setDouble(16, Double.parseDouble(innerList.get(j).toString())) ; //   TOTAL_TAX DECIMAL(30, 2) DEFAULT 0.00,

 stmt.setDouble(17, Double.parseDouble(innerList.get(j).toString())) ; // 

You're trying to parse a string to a double value. But the string is not double type that lead to NumberFormatException. For example:

Double a = Double.parseDouble("asd"); //java.lang.NumberFormatException occurs

There is a problem with your for loop. You should take out stmt.executeBatch(); conn.commit(); and keep out side of the for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM