我正在尝试创建一个可以接受单词并将其保存到数据库的电报机器人(将来我想将其转换为学习西班牙语单词的助手)
存在一个问题,当再次调用该方法添加单词时,线程 Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException 发生异常
我的数据库连接和添加单词的代码:
import java.sql.Connection
import java.sql.DriverManager
object SQLiteConnection {
private var connection: Connection? = null
fun connect(databasePath: String) {
val url = "jdbc:sqlite:$databasePath"
try {
connection = DriverManager.getConnection(url)
println("Connection to SQLite has been established.")
} catch (e: Exception) {
println(e.message)
}
}
fun getConnection(): Connection? {
return connection
}
fun closeConnection() {
try {
connection?.close()
println("DB connection was closed")
} catch (e: Exception) {
println(e.message)
}
}
fun addWord(wordCategoryId: Int, inSpanish: String, inRussian: String){
connection?.use { conn ->
val statement = conn.prepareStatement(
"INSERT INTO Words (word_category_id, in_spanish, in_russian) VALUES (?, ?, ?)"
)
statement.setInt(1, wordCategoryId)
statement.setString(2, inSpanish)
statement.setString(3, inRussian)
println("Word added to the database: $inRussian, $inSpanish, $wordCategoryId")
statement.executeUpdate()
}
}
主代码:
import DB.SQLiteConnection
import Users.UserManager
import Users.greetingMessageForUser
import com.github.kotlintelegrambot.bot
import com.github.kotlintelegrambot.dispatch
import com.github.kotlintelegrambot.dispatcher.command
import com.github.kotlintelegrambot.dispatcher.text
import com.github.kotlintelegrambot.entities.ChatId
fun main() {
val databasePath = "C:\\sqlite\\spanish.db"
SQLiteConnection.connect(databasePath)
SQLiteConnection.createTables()
val userManager = UserManager()
val bot = bot {
token = "TOKEN"
dispatch {
command("start") {
println("Received /start command")
val user = userManager.getUserInfo(message)
println("User ID: ${user.id}, Username: ${user.username}, First Name: ${user.firstName}, Last Name: ${user.lastName}")
bot.sendMessage(ChatId.fromId(message.chat.id), text = greetingMessageForUser(user.firstName))
bot.sendMessage(ChatId.fromId(message.chat.id), text = "Пока доступны следующие команды: Добавление слова в БД: /addWord.)
SQLiteConnection.addUser(user.id,user.username, user.firstName, user.lastName)
}
command("addWord") {
bot.sendMessage(
ChatId.fromId(message.chat.id),
text = "Введите русское слово:"
)
text {
val russianWord = text ?: "Empty message"
println("Received message: $russianWord")
SQLiteConnection.addWord(1, "qwe", russianWord)
println("Word $russianWord was added to DB")
bot.sendMessage(ChatId.fromId(message.chat.id), text = "Слово $russianWord добавлено в базу. Продолжите вводить слова, чтобы добавлять их в БД. Чтобы прекратить, нажмите /stopAdd")
}
}
}
}
bot.startPolling()
}
启动程序后,可以添加一个单词,但是当我再次点击/start时,错误如下:
Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
at java.base/java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:756)
at java.base/java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:778)
at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:170)
at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:194)
at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:169)
at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:194)
at com.github.kotlintelegrambot.dispatcher.Dispatcher.handleUpdate(Dispatcher.kt:97)
at com.github.kotlintelegrambot.dispatcher.Dispatcher.checkQueueUpdates(Dispatcher.kt:40)
at com.github.kotlintelegrambot.dispatcher.Dispatcher.access$checkQueueUpdates(Dispatcher.kt:17)
at com.github.kotlintelegrambot.dispatcher.Dispatcher$checkQueueUpdates$1.invokeSuspend(Dispatcher.kt)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@32d3b4a0, java.util.concurrent.Executors$FinalizableDelegatedExecutorService@5deb4038]
我尝试在每种方法中打开和关闭数据库连接,但没有帮助