0
def jdbcReader(user: String, pwd: String, url: String, id: Int): List[mutable.Map[String, String] = {
   var KeyVal = mutable.Map[String, String]()

   var connection: Connection = null
   try {

      connection = DriverManager.getConnection(url, user, pwd)
      val statement = connection.createStatement()
      val resultSet = statement.executeQuery("SELECT Nam, Value FROM tablename WHERE id=?".replace("?", id.toString))
      while (resultSet.next()) {
         val name = resultSet.getString("Nam")
         val value = resultSet.getString("Value")
         // println("name , value = " + name + ", " + value)
      }

   } catch {
      case e => e.printStackTrace()
         val t = e.getMessage()
   }
}

How do I add element to list of map and return from this method? I am sure you have already figured I am new to Scala

smac89
  • 39,374
  • 15
  • 132
  • 179
testkir
  • 1
  • 1
  • Can you clarify exactly what you are trying to add to this List? An empty map? – sinanspd Nov 05 '19 at 15:10
  • trying to add Key & value pair string to map of list – testkir Nov 05 '19 at 15:25
  • you have a list of maps not a map of list. I surely don't understand why you are returning a list of Map either. A simple Map suffices here, doesn't it? – sinanspd Nov 05 '19 at 15:27
  • var KeyVal =mutable.Map[String, String] var connection:Connection = null try { val name = resultSet.getString("Nam") val value = resultSet.getString("Value") KeyVal += (name -> value) } } catch { case e => e.printStackTrace() val t =e.getMessage() } } – testkir Nov 05 '19 at 15:32
  • It keeps throwing type mismatch when i add a element KeyVal += (name -> value) – testkir Nov 05 '19 at 15:34
  • what is the type of `resultSet`? – hellmean Nov 05 '19 at 15:45
  • also change the return type from `List[mutable.Map[String, String]]` to `mutable.Map[String, String]` that would fix your type mismatch issue. – hellmean Nov 05 '19 at 15:48

1 Answers1

0

The code has a lot of problems causing clarity issues but I will try to answer your question to the best of my understanding.

def jdbcReader(user:String,pwd:String, url: String, id:Int): Map[String, String] ={

   try {

      val connection = DriverManager.getConnection(url, user, pwd)
      val statement = connection.createStatement()
      val resultSet = statement.executeQuery(s"SELECT Nam, Value FROM tablename WHERE id=${id.toString}")


      resultSet.map(e => (e.getString("Name"), e.getString("Value")).toMap

       //Or if you want a hashmap
       // resultSet.map(e=>(e.getString("Name"), e.getString("Value")).groupBy(_._1).map { case (k,v) => (k,v.map(_._2))}


   } catch {
     case e : Exception => 
       e.printStackTrace()
       val t = e.getMessage()      
    }
 }

We dont' recommend using var in Scala. Like ever, unless you really, really have to. So instead of trying to get the results and add them to a map, we will construct a map with these entries on the go.

1) We take the results and map them to a tuple (pair) of key and value

2) Simply call .toMap to turn that into a Map

2.1) You can also do a groupBy, which basically groups all these pairs by key, and later call .map to construct a HashMap

Note, I will be suggesting some ideas that might be slightly advanced for a new comer, however I highly recommend taking the time to familiarizing yourself with these ideas as they will be of big help to you in the future

If for any reason you need to update this Map in the future, you should either look into the idea of function composition, where you would construct a new, updated instance of the Map and pass it to where ever it needs to go through composition. Or, in the cases, where absolutely have to maintain a shared state, please look into State Monads or cats.effect.Ref

This solution assumes that resultSet is a Collection. However I have to say, I find it very difficult to believe a database operation, just returns. That operation should probably be wrapped in an IO and return a future and the whole thing should return a Either or a Try. We don't like throwing exceptions in Scala either. I will leave those as an exercise to you as these suggestions are outside the scope of the question.

sinanspd
  • 2,589
  • 3
  • 19
  • 37