scala 连接 mysql

时间:2023-01-16 05:05:13

code:

import java.sql.{ResultSet, DriverManager}

import com.mysql.jdbc.Connection

object hoursAvg {

val url = "jdbc:mysql://IP/dB"
val user = "username"
val password = "password"
val host = "IP"
val database = "database"

def main(args: Array[String]): Unit = {
Class.forName("com.mysql.jdbc.Driver").newInstance()
val conn = DriverManager.getConnection(url, user, password)
println("hello")

try {
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)

val rs = statement.executeQuery("select s.*, a.UtilityAccountID from AccountStats s, Account a where a.AccountID=s.AccountID limit 10")

while (rs.next) {
val accountid = rs.getString("AccountID")
val updatedate = rs.getString("UpdateDate")
val period = rs.getString("Period")
val statstype = rs.getString("StatsType")
val statsval = rs.getString("StatsVal")
val utilityaccountid = rs.getString("UtilityAccountID")
println("%s, %s, %s, %s, %s, %s".format(accountid, updatedate, period, statstype, statsval, utilityaccountid))
}

}
catch {
case _ : Exception => println("===>")
}
finally {
conn.close()
}
}

}

sbt:

name := "hoursAvg"

version := "1.0"

val apacheSpark = "org.apache.spark" %% "spark-core" % "1.2.0"

val apacheSQL = "mysql" % "mysql-connector-java" % "5.1.37"

val apacheSSQL = "org.apache.spark" % "spark-sql_2.10" % "1.2.0"

lazy val commonSettings = Seq(
organization := "com.gws",
version := "0.1.0",
scalaVersion := "2.10.4"
)

lazy val root = (project in file(".")).
settings(commonSettings: _*).
settings(
name := "hoursAvg",
libraryDependencies ++= Seq (
apacheSQL,
apacheSSQL,
apacheSpark.
exclude("com.esotericsoftware.kryo", "kryo") .
exclude("javax.activation", "activation") .
exclude("commons-beanutils", "commons-beanutils") .
exclude("commons-beanutils", "commons-beanutils-core") .
exclude("commons-logging", "commons-logging") .
exclude("commons-collections", "commons-collections") .
exclude("org.apache.hadoop", "hadoop-yarn-common") .
exclude("org.eclipse.jetty.orbit", "javax.transaction") .
exclude("org.eclipse.jetty.orbit", "javax.servlet") .
exclude("org.eclipse.jetty.orbit", "javax.mail.glassfish") .
exclude("org.eclipse.jetty.orbit", "javax.activation")
)
)