scala 查询数据

1、定义数据库连接

package com.web.dataSource

import com.alibaba.druid.pool.DruidDataSource

object MySqlDataSource {

  val driver = "com.mysql.jdbc.Driver"
  val url = "jdbc:mysql://127.0.0.1:3306"
  val username = "root"
  val password = "root"

  val connectionPool =  new DruidDataSource()
  connectionPool.setUsername(username)
  connectionPool.setPassword(password)
  connectionPool.setDriverClassName(driver)
  connectionPool.setUrl(url)
  connectionPool.setValidationQuery("select 1")
  connectionPool.setInitialSize(15)
  connectionPool.setMinIdle(10)
  connectionPool.setMaxActive(100)
  connectionPool.setRemoveAbandoned(true)
  connectionPool.setRemoveAbandonedTimeoutMillis(180000)
  connectionPool.setMaxWait(5000)
  connectionPool.setTestOnBorrow(false)
  connectionPool.setTestOnReturn(false)

}

2、执行查询

def getOptions(uid:Int) ={

  val connection = MySqlDataSource.connectionPool.getConnection
  var sql = 
           s""" select username,password,sex
            |from user 

            |where uid = ?

           """.stripMargin

var stmt = connection.prepareStatement(sql)

stmt.setInt(1, uid)

var resultSet = stmt.executeQuery()

var resultListMap = List[Map[String,String]]()

//获取结果

while(resultSet.next()){

resultListMap = resultListMap :+ Map(

                                                             "username"->resultSet.getString("username"),

                                                              "password"->resultSet.getString("password"),

                                                              "sex"->resultSet.getInt("sex"),

                                                           )

}

//关闭连接

stmt.close()

connection .close()

//返回结果

resultListMap

}

    

猜你喜欢

转载自blog.csdn.net/qq_29777207/article/details/81329597