How to insert Java ArrayList into MySQL table?

Can someone tell me how can I insert Arraylist values ​​into a MySQL table as one row?

For example, insert “crime, drama, action” in the “genres” column of the “featuredfilms_INFO” table.

This is part of my code:

int i = 0;
List<String> genre = new ArrayList<String>();
.
.
.
Elements elms1 = doc.select("div.infobar"); 
Elements links1 = elms1.select("a[href]");
for (Element link1 : links1){
    if (link1.attr("href").contains("/genre/")) {
        genre.add(links1.get(i).text());
        i++;
    }
}
System.out.println("movie genres:" + genre); 
.
.
try {
     String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
     PreparedStatement preparedStmt = conn.prepareStatement(query);
     preparedStmt.setString (1, ID);
     preparedStmt.setString (2, genre);
   .
   .
   .
}

My problem is that I cannot use setStringfor a genre, since it is not a type string. I am a bit confused since at the beginning I defined the genre as a string, but after some searching, I found that in Java for dynamic arrays I should use ArrayList.

Can someone explain to me in detail what should I do and why?

+4
source share
2 answers

.

 String comma="";
 StringBuilder allGenres = new StringBuilder();
 for (String g: genre) {
    allGenres.append(comma);
    allGenres.append(g);
    comma = ", ";
 }

 String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
 PreparedStatement preparedStmt = conn.prepareStatement(query);
 preparedStmt.setString (1, ID);
 preparedStmt.setString (2, allGenres.toString());

 preparedStmt.setString (2, genre.toString());

, , .

+4

, , List<String> , . . List .

, ID, List<String> genre , :

String query = "INSERT into featuredfilms_INFO (movieId, genres)" + "VALUES (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, ID);
for (String realGenre : genre) {
    preparedStmt.setString (2, realGenre);
    preparedStmt.executeUpdate();
}
+2

Source: https://habr.com/ru/post/1546877/


All Articles