Scala:读取MySQL中数据(示例)

1.导入mysql的jdbc

  <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
</dependency>

2.示例如下

import java.sql.{Connection, DriverManager}

object mysqlApp {
  def main(args: Array[String]): Unit = {
    val username = "root"
    val password = "1234"
    val drive = "com.mysql.jdbc.Driver"
    val url = "jdbc:mysql://localhost:3306/mysql"
    var connection: Connection = null
    try {
    	//在spark中如果不写会出错
      classOf[com.mysql.jdbc.Driver]
      connection = DriverManager.getConnection(url, username, password)
      val statement = connection.createStatement()
      val resultSet = statement.executeQuery("select user from user")
      while (resultSet.next()) {
        println(resultSet.getString("user"))
      }
    } catch {
      case e: Exception=> e.printStackTrace()
    } finally {
      connection.close()
    }
  }
}
posted @ 2019-06-13 12:26  drl_blogs  阅读(2027)  评论(0编辑  收藏  举报