Jury A
Jury A

Reputation: 20052

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 ?

Upvotes: 2

Views: 3498

Answers (3)

JIBINA
JIBINA

Reputation: 21

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

Upvotes: 0

Shila Mosammami
Shila Mosammami

Reputation: 1067

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

Upvotes: 0

Jain
Jain

Reputation: 984

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

Upvotes: 2

Related Questions