这是我的代码。问题是它根据循环中的行数插入数据库,而不是只插入一次。如代码所示,它从文件中获取行数,并尝试提取一些信息以存储在数据库中。例如,如果该行有 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();
}
}