Scala中貌似没有try-with的概念,在Java中则可以使用try-with自动释放连接资源,如:输入输出流、数据库连接。
在Scala中如果想要实现自动释放数据库的连接资源时,需要自己封装。借鉴网上大神的博客,给大家分享一下我自己的Scala jdbc操作工具类。
case class CloseAble[A <: {def close() : Unit}](a: A) {
def map[B](f: A => B): B =
try f(a)
finally {
if (a != null){
a.close()
}
}
def flatMap[B](f: A => B): B = map(f)
}
初始化数据库连接对象
private def initConnection(): Unit = {
try {
Class.forName(this._driverClassName).newInstance()
this.conn = DriverManager.getConnection(this._url, this._user, this._password)
} catch {
case e: Exception => {
e.printStackTrace()
}
}
}
查询模型函数
def queryModel[A](sql: String)(implicit f: ResultSet => List[A]): List[A] = {
initConnection()
CloseAble(this.conn).flatMap {
conn =>CloseAble(conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
.flatMap {
stmt =>CloseAble(stmt.executeQuery()).map {
rs => f(rs)
}
}
}
}
测试
object Test {
implicit def f1(rs: ResultSet): List[Int] = {
val data: ListBuffer[Int] = ListBuffer()
while (rs.next()) {
data.append(rs.getInt("id"))
}
return data.toList
}
def main(args: Array[String]): Unit = {
val dbHelper = RelationDbHelper()
for (i <- 1 to 1000) {
val data = dbHelper.queryModel[Int]("select * from etl_new_banner_store")(f1)
println(i)
println(data)
}
}
}
感谢大神[吐思圈] https://www.jianshu.com/u/a019e1b214c9
https://www.jianshu.com/p/fbd3cd650fe9