I am testing the code below, does a basic database query. It works fine when I run it from the CLI using "scala dbtest.scala", but gives me compile errors when I try to compile it with scalac :
[sean@ibmp2 pybackup]$ scalac dbtest.scala dbtest.scala:5: error: expected class or object definition val conn_str = "jdbc:mysql://localhost:3306/svn?user=svn&password=svn" ^ dbtest.scala:8: error: expected class or object definition classOf[com.mysql.jdbc.Driver] ^ dbtest.scala:11: error: expected class or object definition val conn = DriverManager.getConnection(conn_str) ^ dbtest.scala:12: error: expected class or object definition try { ^ four errors found
import java.sql.{Connection, DriverManager, ResultSet};
import java.util.Date
// Change to Your Database Config
val conn_str = "jdbc:mysql://localhost:3306/svn?user=xx&password=xx"
// Load the driver
classOf[com.mysql.jdbc.Driver]
// Setup the connection
val conn = DriverManager.getConnection(conn_str)
try {
// Configure to be Read Only
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
// Execute Query
val rs = statement.executeQuery("SELECT * FROM backup")
// Iterate Over ResultSet
var svnFiles = Set[String]()
while (rs.next) {
val repos = rs.getString("repos")
val lm = rs.getDate("lastModified")
val lb = rs.getDate("lastBackedup")
if (lm.getTime() > lb.getTime()) {
println(repos + " needs backing up")
svnFiles += repos
}
else {
println(repos + " doesn't need backing up")
}
}
println(svnFiles)
}
finally {
conn.close
}
You need either a class, object, or trait at the top level to make it a legal source to compile. scala
interpreter expects definitions and expressions, whereas scalac
expects something that can turn into Java .class
files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With