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?
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With