2

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 ?

3
  • Check this .This might help stackoverflow.com/questions/12127407/… Commented Nov 3, 2012 at 5:15
  • 4
    What you have tried ? Did you get any errors? Commented Nov 3, 2012 at 5:15
  • It's probably a bad idea anyway. Store each element as a row in an additional table. Commented Nov 3, 2012 at 7:33

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
  1. List itemArrayList<String> nameSet = new ArrayList<>(); nameSet.add("Item 1"); nameSet.add("Item 2"); nameSet.add("Item 3");

Step 2: Establish a connection to the MySQL database Connection connection = DriverManager.getConnection(url,username,password);

Step 3: Create an SQL insert statement String insertQuery = "INSERT INTO your_table_name (column_name) VALUES (?)";

Step 4: Concatenate the ArrayList elements into a single string StringBuilder concatenatedNames = new StringBuilder(); for (String item : nameSet) { concatenatedNames.append(item).append(", "); } concatenatedNames.setLength(concatenatedNames.length() - 2); Remove the last ", "

Step 5: Execute the SQL statement PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); preparedStatement.setString(1, concatenatedNames.toString()); preparedStatement.executeUpdate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.