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()
}
}
}