【发布时间】:2016-02-05 01:54:57
【问题描述】:
我有一个应用程序可以扫描文本文件中的某些单词,如果找到这些单词,则更新数据库表。我逐行扫描文件中的某些单词,例如这样
public void scanFile(File toBeScanned) {
try {
InputStream instream = new FileInputStream(toBeScanned);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, 1 line at the time
do {
line = buffreader.readLine();
if (line.contains("word1"))
doInsert("word1", ourJavaTimestampObject , id ,"Test_Child");
if (line.contains("word2"))
doInsert("word2", ourJavaTimestampObject, id ,"Test_Child");
if (line.contains("word3"))
doInsert("word3", ourJavaTimestampObject, id, "Test_Child");
} while (line != null);
我的程序成功地提取了这些词,但正在用它们多次填充数据库。例如。 word1,word2,word2 被发送到 DB,第二次点击时 DB 有 word1,word2,word2,word1,word2,word2 等等。
我通过单击按钮调用 scanFile 方法,并且任何时候发生的单词都会重新输入到数据库中。
我希望我的程序只插入一个单词的每个实例一次。所以在文件被逐行读取之后,最好的做法可能是清空文件?或者我的循环可能需要不同的方法
这里也是插入方法
public void doInsert(String word, java.sql.Timestamp ourJavaTimestampObject, int userID , String child) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
st.executeUpdate("\n" +
"INSERT IGNORE INTO FLAGS (FLAG_WORD, FLAG_DATE, FLAG_USER, FLAG_CHILD)\n" +
"VALUES ('" + word + "' , '" + ourJavaTimestampObject + "' , '" + userID + "','" + Register.child + "')");
con.close();
} catch (SQLException ex) {
} catch (ClassNotFoundException e) {
}
}// end method insert
非常感谢任何建议,我已经坚持了好几个小时了。
【问题讨论】:
-
你使用了哪种方法?
标签: java mysql file loops bufferedreader