简体   繁体   中英

How to insert ArrayList data type into MySQL database in Java

I have the following variable:

 ArrayList<String> NameSet = new ArrayList<String>();

That I filled it with items in a loop using the add method as follows:

  NameSet.add(Body.item(t).getAttributes().getNamedItem("name").getNodeValue());

How can I insert the list in a Long text data type in MySQL database?

There is no direct way of inserting an array list into a row in mysql. But if you want to insert the names in a single row, then instead of putting them into arraylist you could just save them into a string variable and maybe separate them with a 'character' and then use insert query to save it in Db.

Otherwise you have to make a separate method to convert this this arraylist into a string and then do the above

Insert batch would be the good solution:

supposing connection is your mysql jdbc connection:

   String queryInsert="INSERT INTO  TableName ( name, field2 ,...) values (?,?,..)";
        try( PreparedStatement ps= connection.prepareStatement(queryInsert);){
             connection.autoCommit(false);
            for(String name:NameSet){
            ps.setString(1,name);
             ....
      }
    ps.executeBatch();
    connection.commit();
} catch (SQLException e) {
    con.rollback();
    System.err.format(e.getSQLState(), e.getMessage());
} 

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