Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program works when run with scala, get compile errors when try to compile it with scalac

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
}

like image 662
fred basset Avatar asked Jan 10 '11 21:01

fred basset


1 Answers

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.

like image 75
Eugene Yokota Avatar answered Sep 21 '22 13:09

Eugene Yokota