步骤:
1)MySQL的驱动
2)Connection 重量级的获取过程。可以使用POOL优化
3)Statement 执行的类
4)ResultSet 结果的封装
5)Close
在pom中添加scala、hadoop、Mysql驱动依赖包:
2.11.8
2.6.5
org.scala-lang
scala-library
${scala.version}
org.apache.hadoop
hadoop-client
${hadoop.version}
mysql
mysql-connector-java
5.1.28
编写代码:
import java.sql.DriverManager
object ScalaJDBCApp {
def main(args:Array[String]):Unit = {
val url = "jdbc:mysql://hadoop001:3306/ruoze_g6"
val user = "root"
val password = "123456"
//classOf[com.mysql.jdbc.Driver]//或者使用 Class.forName("com.mysql.jdbc.Driver")
Class.forName("com.mysql.jdbc.Driver")
val sql = "select city_id,city_name from city_info"
val connection = DriverManager.getConnection(url,user,password)
val stmt = connection.createStatement()
val rs = stmt.executeQuery(sql)
while(rs.next()){
val cityid = rs.getInt(1)
val cityname = rs.getString(2)
println(cityid+"....."+cityname)
}
rs.close()
stmt.close()
connection.close()
}
}
可能出现的异常:
1)java.sql.SQLException: No suitable driver found for jdbc://mysql://hadoop001:3306/ruoze_g6有可能是驱动没加进来,有可能是连接地址url写错了
2)SQLException: Access denied for user 'root'@'192.168.119.1' (using password: YES)数据库、表访问权限的异常。可能是用户权限不够,也可能是ip的权限不够。所以在mysql中修改访问权限:
grant all privileges on *.* to root@'%' identified by '123456';
表示root用户可以在任何ip都可以访问任何库,密码是123456
但是一般都不会用原生的,都是使用框架。