Scala连接mysql导出数据

package cn.kgc.cha01.mysql

import scala.reflect.ClassTag
//使用
object Test {
  def main(args: Array[String]): Unit = {
    val dao = Dao()
    case class Stu(name:String,sex:String,age:Int,grade:String,number:Int){
      override def toString: String = s"$name,$sex,$age,$grade,$number"
    }
    val strArrToOrder = (arr:Array[String]) => Stu(
      arr(0).toString,
      arr(1).toString,
      arr(2).toInt,
      arr(3).toString,
      arr(4).toInt
    )
    val sql = "select * from stu"
    implicit val c = ClassTag(classOf[Stu])
    val o: Option[Array[Stu]] = dao.select(strArrToOrder)(sql)
    if (o.isEmpty){
      println("Exption")
    }else{
      o.get.foreach(println)
    }
  }

}

package cn.kgc.cha01.mysql

import java.io.{File, FileReader}
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import java.util.Properties

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

class Dao(conf:Properties=null) {
  private var _conf:Properties = conf
  private var driver:String = null
  private var url:String = null
  private var username:String = null
  private var password:String = _
  init
  private def init:Unit= {
    if(null==_conf){
      _conf = new Properties()
      try {
        var path = Thread.currentThread().
          getContextClassLoader.getResource("")
          .getPath
        path = new File(path)
          .getParentFile.getParentFile
          .getParentFile.getAbsolutePath + "/config/datasource.properties"
        println(path)
        _conf.load(new FileReader(path))
        driver = _conf.getProperty("mysql.driver")
        url = _conf.getProperty("mysql.url")
        username = _conf.getProperty("mysql.username")
        password = _conf.getProperty("mysql.password")
        if (null==driver || null==url || null==username || null==password){
          println(driver,url,username,password)
          throw new NullPointerException("配置有空指针")
        }
        Class.forName(driver)
      } catch {
                //这里偷懒 使用多态
//        case e:FileNotFoundException => println("文件找不到")
//        case e:NullPointerException => println("空指针异常")
        case e:Throwable=> {
          e.printStackTrace()
          System.exit(-1)
        }
      }
    }
  }
  //排除空指针
  private def close(closes:AutoCloseable*) = closes.filterNot(null==_).foreach(e=>e.close())
  private def getCon:Connection =
    DriverManager.getConnection(url,username,password)
  private def getPst(con:Connection,sql:String,parms:Seq[Any]):PreparedStatement = {
    val pst = con.prepareStatement(sql)
    if (!parms.isEmpty){
      //此方法可以是一个
        parms.zipWithIndex.foreach(tp2=>{
          pst.setObject(tp2._2+1,tp2._1)
      })
    }
    pst
  }
//  def update(sql:String,params:Object*):Option[Int] = {
//      var opt:Option[Int] = null
//      var con:Connection = null
//      var pst:PreparedStatement = null
//      try{
//        con = getCon
//        pst = getPst(con,sql,params)
//        opt = Some(pst.executeUpdate())
//      }catch {
//        case e:Throwable => println(e.getMessage)
//      }finally {
//        close(pst,con)
//      }
//      opt
//  }
  def select[T](f:Array[String]=>T)(sql:String,params:Any*)(implicit c:ClassTag[T]):Option[Array[T]] = {
    var opt:Option[Array[T]] = None
    var con:Connection = null
    var pst:PreparedStatement = null
    var rst:ResultSet = null
    try{
      con = getCon
      pst = getPst(con,sql,params)
      rst = pst.executeQuery()
      val  buffer = ArrayBuffer[T]()
      val columnCount = rst.getMetaData.getColumnCount
      val arr = new Array[String](columnCount)
      val seq = for(i<-0 until columnCount) yield i
      while (rst.next()){
        seq.foreach(ix=>arr(ix)=rst.getString(ix+1))
        buffer += f(arr)
      }
      opt = Some(buffer.toArray(c))
    }catch {
      case e:Throwable => e.printStackTrace()
    }
    opt
  }
}
object Dao{
  def apply(conf: Properties = null): Dao = new Dao(conf)
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

布丁味

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值