简体   繁体   English

Kotlin 数据库连接错误

[英]Kotlin database connectivity error

Exception in thread "main" kotlin.KotlinNullPointerException at Kotlin.main(DB.kt:4) Kotlin.main(DB.kt:4) 处的线程“main”kotlin.KotlinNullPointerException 中的异常

can anyone explain me what is this and what should i do to handle this exception?谁能解释一下这是什么,我应该怎么做来处理这个异常?

object Kotlin {
    @JvmStatic fun main(args: Array<String>) {
        val conn: Connection = null!!
        val url = "jdbc:mysql://localhost:3306/"
        val dbName = "db-01"
        val driver = "com.mysql.jdbc.Driver"
        try {
            Class.forName(driver).newInstance()
            conn = DriverManager.getConnection("jdbc:mysql://localhost/student")
            println("Connected to the database")
            conn.close()
            println("Disconnected from database")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

val conn: Connection = null!!

The !! !! 'casts' a nullable type to a non-null type, if the value is not null . “类型转换”空类型到一个非空的类型,如果该值不null If it is null , it throws a NullPointerException .如果它是null ,它会抛出一个NullPointerException

Thus, executing null!!因此,执行null!! results in a NullPointerException .导致NullPointerException
Instead, use a lateinit var , or make the Connection nullable.相反,使用lateinit var ,或使Connection空。

It is perfectly fine not to initialize local val , if you're going to initialize it later:如果您以后要初始化它,最好不要初始化本地val

fun main(args: Array<String>) {
    val conn: Connection
    // ... some code ...
    conn = DriverManager.getConnection("jdbc:mysql://localhost/student")
}

And if you do not need the connection outside of try block, you can declare it and initialize it at the same line:如果您不需要try块之外的连接,您可以在同一行声明并初始化它:

try {
    //...
    val conn = DriverManager.getConnection("jdbc:mysql://localhost/student")
    //...
    conn.close()
} catch (e: Exception) {
    e.printStackTrace()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM