【问题标题】:How to connect (Py)Spark to Postgres database using JDBC如何使用 JDBC 将 (Py)Spark 连接到 Postgres 数据库
【发布时间】:2017-01-12 02:53:30
【问题描述】:

我已按照this posting 的说明从现有 Postgres 数据库中读取数据,该数据库中的表名为“objects”,该表由 SQLalchemy 中的Objects 类定义和创建。在我的 Jupyter 笔记本中,我的代码是

from pyspark import SparkContext
from pyspark import SparkConf
from random import random

#spark conf
conf = SparkConf()
conf.setMaster("local[*]")
conf.setAppName('pyspark')

sc = SparkContext(conf=conf)

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
properties = {
    "driver": "org.postgresql.Driver"
}
url = 'jdbc:postgresql://PG_USER:PASSWORD@PG_SERVER_IP/db_name'
df = sqlContext.read.jdbc(url=url, table='objects', properties=properties)

最后一行结果如下:

Py4JJavaError: An error occurred while calling o25.jdbc.
: java.lang.NullPointerException
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:158)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:117)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:237)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:211)
    at java.lang.Thread.run(Thread.java:745)

所以看起来它无法解析表格。如何从这里进行测试以确保我已正确连接到数据库?

【问题讨论】:

    标签: postgresql jdbc apache-spark pyspark apache-spark-sql


    【解决方案1】:

    名称解析问题由org.postgresql.util.PSQLException 指示,不会导致 NPE。问题的根源实际上是一个连接字符串,尤其是您提供用户凭据的方式。乍一看,它看起来像一个错误,但如果您正在寻找快速解决方案,您可以使用 URL 属性:

    url = 'jdbc:postgresql://PG_SERVER_IP/db_name?user=PG_USER&password=PASSWORD'
    

    或属性参数:

    properties = {
        "user": "PG_USER",
        "password": "PASSWORD",
        "driver": "org.postgresql.Driver"
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 2020-02-28
      • 2021-04-07
      • 1970-01-01
      • 2021-03-10
      • 2020-10-26
      • 1970-01-01
      • 2016-08-21
      • 2012-08-21
      相关资源
      最近更新 更多