Maven依赖
<!--注意 底层引用的\org\glassfish\javax.el\3.0.1-b06-SNAPSHOT在仓库中已经移除了我们这里引用其稳定版本-->
<dependency>
<groupId>org.apache.phoenix</groupId>
<artifactId>phoenix-spark</artifactId>
<version>4.14.2-HBase-1.3</version>
<exclusions>
<exclusion>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b06</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
查询
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet, ResultSetMetaData}
import com.alibaba.fastjson.JSONObject
import scala.collection.mutable.ListBuffer
object PhoenixUtil {
def main(args: Array[String]): Unit = {
//查询语句 select * from "ns1"."us_population"
val list: List[JSONObject] = queryList("select * from \"ns1\".\"us_population\"")
println(list)
}
private val phoenixUrl = "jdbc:phoenix:zjj101,zjj102,zjj103:2181"
def queryList(sql: String): List[JSONObject] = {
val rsList: ListBuffer[JSONObject] = new ListBuffer[JSONObject]
//注册驱动
Class.forName("org.apache.phoenix.jdbc.PhoenixDriver")
//建立连接
val conn: Connection = DriverManager.getConnection(phoenixUrl)
//创建数据库操作对象
val ps: PreparedStatement = conn.prepareStatement(sql)
//执行SQL语句
val rs: ResultSet = ps.executeQuery()
val rsMetaData: ResultSetMetaData = rs.getMetaData
//处理结果集
while (rs.next()) {
val usPopulation = new JSONObject()
for (i <- 1 to rsMetaData.getColumnCount) {
usPopulation.put(rsMetaData.getColumnName(i), rs.getObject(i))
}
rsList.append(usPopulation)
}
//释放资源
rs.close()
ps.close()
conn.close()
rsList.toList
}
}
执行输出结果:
List({“POPULATION”:3844829,”CITY”:”Los Angeles”,”STATE”:”CA”}, {“POPULATION”:2842518,”CITY”:”Chicago”,”STATE”:”IL”}, {“POPULATION”:8143197,”CITY”:”NewYork”,”STATE”:”NY”})