Kotlin数据库连接错误
线程“main”中的异常kotlin.KotlinNullPointerException在Kotlin.main(DB.kt:4)
任何人都可以解释我是什么,我应该怎么做来处理这个异常?
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!!
!!
如果值不为null,则将可空类型转换为非null类型。 如果它为null
,则抛出一个NullPointerException
异常。
因此,执行null!!
导致NullPointerException
。
而是使用lateinit var
,或者使Connection
空。
如果以后要初始化,那么不要初始化本地val
:
fun main(args: Array<String>) { val conn: Connection // ... some code ... conn = DriverManager.getConnection("jdbc:mysql://localhost/student") }
如果你不需要try
块之外的连接,你可以声明它并在同一行初始化它:
try { //... val conn = DriverManager.getConnection("jdbc:mysql://localhost/student") //... conn.close() } catch (e: Exception) { e.printStackTrace() }