SQLException:使用SQLite和Scala的未知数据库

时间:2016-01-17 16:21:19

标签: scala sqlite

我有对象DictionarySqlLiteDao,它应该在初始化期间创建它不存在的表。但我有异常,尽管数据库是在文件系统中创建的。帮我弄清楚它的原因。这是我的代码:

object DictionarySqlLiteDao extends Dao[Word] {

private val CREATE_WORD_TABLE_SQL = "CREATE TABLE IF NOT EXISTS thelper.WORD " +
        "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "WORD TEXT NOT NULL, " +
        "UKR TEXT NOT NULL, " +
        "ENG TEXT NOT NULL, " +
        "EXAMPLE TEXT)"
private val SAVE_WORD_SQL = "INSERT INTO WORD(WORD, UKR, ENG, EXAMPLE" +
        "VALUES(?, ?, ?, ?)"
private val connection: Connection = {
    Class.forName("org.sqlite.JDBC")
    DriverManager.getConnection("jdbc:sqlite:thelper")
}

{
    connection.createStatement().executeUpdate(CREATE_WORD_TABLE_SQL)
}

override def save(word: Word): Word = {
    val statement = connection.prepareStatement(SAVE_WORD_SQL, Statement.RETURN_GENERATED_KEYS)
    statement.setString(1, word.word)
    statement.setString(2, word.translation("ukr"))
    statement.setString(3, word.translation("eng"))
    statement.setString(4, word.example.orNull)
    statement.executeUpdate()
    val id = statement.getGeneratedKeys.getInt(1)
    word.copy(id = id)
}

def main(args: Array[String]) {
    println(connection == null) // here I get false
    println(connection.createStatement().execute("select date('now')")) // here I get true
    val w = save(Word(-1, "germanWord", Map("ukr" -> "ukrTranslation", "eng" -> "engTranslation"), Option.empty[String])) // and here I get an Exception
    println(w)
}

}

这是我得到的一个例外:

Exception in thread "main" java.lang.ExceptionInInitializerError
at thelper.Dictionary.dao.DictionarySqlLiteDao.main(DictionarySqlLiteDao.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.sql.SQLException: unknown database thelper
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at thelper.Dictionary.dao.DictionarySqlLiteDao$.<init>(DictionarySqlLiteDao.scala:23)
at thelper.Dictionary.dao.DictionarySqlLiteDao$.<clinit>(DictionarySqlLiteDao.scala)
... 6 more

1 个答案:

答案 0 :(得分:1)

据我记得你应该指定数据库的完整路径,在你的内存中它应该像submodules那样:

thelper.db

P.S。之后,您可以省略数据库名称:DriverManager.getConnection("jdbc:sqlite:thelper.db")`

P.P.S您可以使用三引号来编写多行字符串,如

"CREATE TABLE IF NOT EXISTS WORD " + ....