标签:obj str sele except mysq tin 获取 getc sql
步骤:
1)MySQL的驱动
2)Connection 重量级的获取过程。可以使用POOL优化
3)Statement 执行的类
4)ResultSet 结果的封装
5)Close
在pom中添加scala、hadoop、Mysql驱动依赖包:
<properties>
<scala.version>2.11.8</scala.version>
<hadoop.version>2.6.5</hadoop.version>
</properties>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
编写代码:
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
但是一般都不会用原生的,都是使用框架。
【Scala】Scala使用JDBC连接Mysql/权限问题
标签:obj str sele except mysq tin 获取 getc sql
原文地址:https://www.cnblogs.com/huomei/p/12103714.html