これは私のコードです。問題は、1回だけ挿入するのではなく、ループ内の行数に基づいてデータベースに挿入することです。コードが示すように、ファイルから行数を取得し、データベースに保存するためにいくつかの情報を抽出しようとします。たとえば、行に5行ある場合、その情報はデータベースに5回保存されます。
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class Movie_Info {
private static String user = "root";
private static String pw = "";
private static String dbUrl = "jdbc:mysql://127.0.0.1/NLD";
private static String dbClass = "com.mysql.jdbc.Driver";
public static String scraped_commentsInsert
= "INSERT INTO scraped_comments (id, movie_title,user_comments) VALUES (?,?,?)";
private Connection con;
private Statement st;
private PreparedStatement multiInsert;
public Movie_Info(String id, String movie) throws IOException, SQLException{
try {
Class.forName(dbClass);
con = DriverManager.getConnection(dbUrl, user, pw);
//con.setAutoCommit(false);
st=con.createStatement();
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
List lines = null;
try{
lines = FileUtils.readLines(new File(movie+"_S1.txt"), "UTF-8");
} catch(Exception ex) {
System.out.println("movie file does not exist: " + movie + " id: " + id);
return;
}
for (Object line : lines) {
String Synopsis = line.toString();
String Released = line.toString();
String Runtime = line.toString();
String Genre = line.toString();
String Director = line.toString();
String Actors = line.toString();
if (String.valueOf(line).startsWith("Synopsis ") ) {
// for quotes
Synopsis = Synopsis.replace(":", " storyline goes like this. ");
Synopsis = Synopsis.replace("'", " ");
// remove comment
Synopsis = Synopsis.replace("Synopsis ", "");
System.out.println(Synopsis);
}
if ( String.valueOf(line).startsWith("Released: ") ) {
Released = Released.replace("'", "''");
Released = Released.replace("Released: ", "");
System.out.println(Released);
}
if (String.valueOf(line).startsWith("Runtime: ")) {
Runtime = Runtime.replace("'", "''");
Runtime = Runtime.replace("Runtime: ", "");
System.out.println(Runtime);
}
if (String.valueOf(line).startsWith("Genres: ") ) {
Genre = Genre.replace("'", "''");
Genre = Genre.replace("Genre: ", "");
System.out.println(Genre);
}
if (String.valueOf(line).startsWith("Director: ") ) {
Director = Director.replace("'", "''");
Director = Director.replace("Director: ", "");
System.out.println(Director);
}
if (String.valueOf(line).startsWith("Actors: ") ) {
Actors = Actors.replace("'", " ");
Actors = Actors.replace("Actors: ", "");
System.out.println(Actors);
} // end if
// int k= st.executeUpdate("INSERT INTO Movie_Infor ( Release_Date,movie_title,Synopsis, Runtime, Genres, Director, Actors) values('"+Released+"','"+movie+"','"+Synopsis+"','"+Runtime+"','"+Genre+"','"+Director+"','"+Actors+"')");
} // end for
con.close();
}
}