程序在使用scala运行时有效,在尝试使用scalac编译时会出现编译错误

fre*_*set 9 scala compilation

我正在测试下面的代码,做一个基本的数据库查询.当我使用"scala dbtest.scala"从CLI运行它时,它工作正常,但是当我尝试使用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
}

Eug*_*ota 12

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.