如何使用Scala的异常处理从JDBC连接类返回连接?

问题描述 投票:0回答:1

我正在尝试创建一个Scala JDBC程序,在该程序中将与Hive建立连接。为此,我编写了以下代码。

var HIVECON: Connection = null
def hiveConnection(): Connection = {
    val conf = new Configuration()
    conf.set("hadoop.security.authentication", "Kerberos")

    // DEV System Properties
    System.setProperty("java.security.krb5.kdc", "ip-address.ec2.internal");
    System.setProperty("java.security.krb5.realm", "DEV.COM");
    // DEV System Properties

    // DEV loginUserFromKeytab
    UserGroupInformation.loginUserFromKeytab("[email protected]", "/home/username/username.keytab");
    // DEV loginUserFromKeytab

    try {
        Class.forName("org.apache.hive.jdbc.HiveDriver")
        if(HIVECON == null || HIVECON.isClosed)
            HIVECON = DriverManager.getConnection("jdbc:hive2://ip-address.ec2.internal:10500/dbname;principal=hive/[email protected]", "username","password")
        else HIVECON
    } catch {
        case s:SQLException => s.printStackTrace()
        case e:Exception    => e.printStackTrace()
    }
}

但是代码在以下行给出了编译错误:enter image description here

[按照我写的方式,catch语句返回UNIT,而我的方法试图返回CONNECTION。有什么方法可以更好地处理异常吗?

scala jdbc
1个回答
0
投票

我将以功能性方式处理异常。

如果您不关心特定的异常,请使用Option

var HIVECON: Option[Connection] = None
def hiveConnection(): Option[Connection] = {
    ...
    try {
        Class.forName("org.apache.hive.jdbc.HiveDriver")

        if(HIVECON == None || HIVECON.isClosed)
            HIVECON = Some(DriverManager.getConnection("jdbc:hive2://ip-address.ec2.internal:10500/dbname;principal=hive/[email protected]", "username","password"))
         HIVECON // return Some(Connection)
    } catch {
        case s:Exception => 
           s.printStackTrace()
           None
    }

如果您关心例外,请使用Try

var HIVECON: Connection = null
def hiveConnection(): Try[Connection] = {
    ...
    Try {
        Class.forName("org.apache.hive.jdbc.HiveDriver")

        if(HIVECON == null || HIVECON.isClosed)
            HIVECON = DriverManager.getConnection("jdbc:hive2://ip-address.ec2.internal:10500/dbname;principal=hive/[email protected]", "username","password")
         HIVECON // return Success(Connection)
    }

如果失败,它将返回Failure(Exception)

请参阅此处的文档:https://docs.scala-lang.org/overviews/scala-book/functional-error-handling.html

© www.soinside.com 2019 - 2024. All rights reserved.