Scala And JDBC
I was writing some small programs yesterday trying to read data from one database and input to another database.Hence,I tried to use Scala to do that.I’ve never write scala to connect to a database using JDBC before,but I am quite surprise with the simplicity of the code.It merely took me 10 minutes to finish writing the code.
Here’s the code
// Import JDBC package from standard Java SDK
import java.sql.{Connection, DriverManager, ResultSet};
class DataReader {
// Load the driver
Class.forName("com.mysql.jdbc.Driver").newInstance;
val connection = DriverManager getConnection "jdbc:mysql://localhost:3306/mail?user=root&password=&characterEncoding=UTF8"
def startReadingData(){
try{
// Create statement for readonly
val statement = conn createStatement (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val rs = statement executeQuery "select * from mail_queues order by id"
// Looping resultset
while (rs next) {
println (rs getLong "id")
}
statement close
}catch {
case e => e printStackTrace
}finally {
connection close
}
}
}
Ok, you maybe wondering,why are so many dots(.) and parentheses missing?In Scala,when you are invoking one function with no or one parameter, you can omit the dot and parentheses. And Scala doesn’t have checked exception, which means you can write the above code without enclosed it with try…catch clause.I included it to make sure the DB connection is properly closed after use.
Happy coding.:)












Thanks for the elegant code. It works well. One bug though, val statement = conn[ection] createStatement…