gpt4 book ai didi

java - 扫描文件中的标记单词时,数据被多次插入数据库

转载 作者:行者123 更新时间:2023-11-29 21:52:14 26 4
gpt4 key购买 nike

我有一个应用程序,可以扫描文本文件中的某些单词,如果找到这些单词,则更新数据库表。我逐行扫描文件中的某些单词,如下所示

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 被发送到数据库,第二次点击数据库有 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

非常感谢任何建议,我已经在这个问题上坚持了几个小时了。

最佳答案

我从问题中了解到的是,您不想再次读取同一文件中的内容。

一种方法是将文件名保存在数据库中(假设文件名是唯一的),并在插入之前检查数据库中的唯一文件名。

第二种方法是按照您的建议清空文件。或者,您可以将“已读”(第 1 行)之类的 header 附加到文件中,该 header 将作为文件已被您读取的指示器。

关于java - 扫描文件中的标记单词时,数据被多次插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33524096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com