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
The code has a lot of problems causing clarity issues but I will try to answer your question to the best of my understanding.
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.