Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert Java ArrayList into a MySQL table?

Could someone kindly tell me how can I insert the values of Arraylist into MySQL table as a single string?

E.g, insert "crime, drama, Action" into column "genres" of a table "featuredfilms_INFO".

This is a 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 setString for genre since it is not of type string. I'm a bit confused since at the beginning I defined genre as string but after some search I found that in Java for dynamic arrays I have to use ArrayList.

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

like image 803
mOna Avatar asked Jul 02 '14 15:07

mOna


2 Answers

Just join all the strings before inserting.

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

Maybe even

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

would even be good enough, but the above solution gives you more freedom how to join the genres.

like image 98
Erich Kitzmueller Avatar answered Nov 03 '22 10:11

Erich Kitzmueller


I guess you're confused because your List<String> is called genre and you try to insert it as is. This won't work. You need to insert every element from the List in your table.

Assuming you have declared and initialized ID variable and that List<String> genre is filled with the right values, then you should only traverse the list and insert every 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();
}
like image 25
Luiggi Mendoza Avatar answered Nov 03 '22 10:11

Luiggi Mendoza