Maven依赖

  1. <!--注意 底层引用的\org\glassfish\javax.el\3.0.1-b06-SNAPSHOT在仓库中已经移除了我们这里引用其稳定版本-->
  2. <dependency>
  3. <groupId>org.apache.phoenix</groupId>
  4. <artifactId>phoenix-spark</artifactId>
  5. <version>4.14.2-HBase-1.3</version>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.glassfish</groupId>
  9. <artifactId>javax.el</artifactId>
  10. </exclusion>
  11. </exclusions>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.glassfish</groupId>
  15. <artifactId>javax.el</artifactId>
  16. <version>3.0.1-b06</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.alibaba</groupId>
  20. <artifactId>fastjson</artifactId>
  21. <version>1.2.62</version>
  22. </dependency>

查询

  1. import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet, ResultSetMetaData}
  2. import com.alibaba.fastjson.JSONObject
  3. import scala.collection.mutable.ListBuffer
  4. object PhoenixUtil {
  5. def main(args: Array[String]): Unit = {
  6. //查询语句 select * from "ns1"."us_population"
  7. val list: List[JSONObject] = queryList("select * from \"ns1\".\"us_population\"")
  8. println(list)
  9. }
  10. private val phoenixUrl = "jdbc:phoenix:zjj101,zjj102,zjj103:2181"
  11. def queryList(sql: String): List[JSONObject] = {
  12. val rsList: ListBuffer[JSONObject] = new ListBuffer[JSONObject]
  13. //注册驱动
  14. Class.forName("org.apache.phoenix.jdbc.PhoenixDriver")
  15. //建立连接
  16. val conn: Connection = DriverManager.getConnection(phoenixUrl)
  17. //创建数据库操作对象
  18. val ps: PreparedStatement = conn.prepareStatement(sql)
  19. //执行SQL语句
  20. val rs: ResultSet = ps.executeQuery()
  21. val rsMetaData: ResultSetMetaData = rs.getMetaData
  22. //处理结果集
  23. while (rs.next()) {
  24. val usPopulation = new JSONObject()
  25. for (i <- 1 to rsMetaData.getColumnCount) {
  26. usPopulation.put(rsMetaData.getColumnName(i), rs.getObject(i))
  27. }
  28. rsList.append(usPopulation)
  29. }
  30. //释放资源
  31. rs.close()
  32. ps.close()
  33. conn.close()
  34. rsList.toList
  35. }
  36. }

执行输出结果:

List({“POPULATION”:3844829,”CITY”:”Los Angeles”,”STATE”:”CA”}, {“POPULATION”:2842518,”CITY”:”Chicago”,”STATE”:”IL”}, {“POPULATION”:8143197,”CITY”:”NewYork”,”STATE”:”NY”})