Scala连接MySQL数据库 2015-04-27 19:00

sbt工程

name := "TryScalaMySql Project"
version := "1.0"
scalaVersion := "2.11.5"
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.33"
exportJars := true

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.sql.DriverManager
import java.sql.Connection

/**
 * A Scala JDBC connection example by Alvin Alexander,
 * <a href="http://alvinalexander.com" title="http://alvinalexander.com">http://alvinalexander.com</a>
 */
object ScalaJdbcConnectSelect {

  def main(args: Array[String]) {
    // connect to the database named "mysql" on the localhost
    val driver = "com.mysql.jdbc.Driver"
    val url = "jdbc:mysql://10.255.1.6/LemonHouse"
    val username = "root"
    val password = "123123"

    // 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,month,house_count FROM house_datastat")
      while ( resultSet.next() ) {
        val id = resultSet.getInt("id")
        val month = resultSet.getString("month")
        val house_count = resultSet.getInt("house_count")
        println("id = " + id + ", month = " + month + ", house_count = " + house_count)
      }
    } catch {
      case e => e.printStackTrace
    }
    connection.close()
  }
}

运行

sbt run
Tags: #Scala #MySQL    Post on Programming