scala jdbc例

1351 ワード

import java.sql.{DriverManager, Connection, ResultSet}
 import java.sql.DriverManager
import java.sql.Connection
object TestDb {

  def main(args: Array[String]): Unit = {
  // connect to the database named "mysql" on the localhost
    val driver = "com.mysql.jdbc.Driver"
    val url = "jdbc:mysql://localhost:3306/easyui"
    val username = "root"
    val password = ""
 
    // there's probably a better way to do this
    var connection:Connection = null
 
    try {
      // make the connection
      Class.forName(driver)
      connection = DriverManager.getConnection(url, username, password)
 
      // create the statement, and run the select query
      val statement = connection.createStatement()
      val resultSet = statement.executeQuery("SELECT id, name FROM easyui_tree")
      while ( resultSet.next() ) {
        val id = resultSet.getString("id")
        val name = resultSet.getString("name")
        println("id, name = " + id + ", " + name)
      }
    } catch {
      case e => e.printStackTrace
    }
    connection.close()
  }
 
}