Skip to main content

JDBC Sources


Spark SQL also includes a data source that can read data from other databases using *JDBC.

Tables from the remote database can be loaded as a DataFrame or Spark SQL temporary view using the Data Sources API. Users can specify the JDBC connection properties in the data source options. user and password are normally provided as connection properties for logging into the data sources

Spark supports the following case-insensitive options:

Property NameMeaning
urlThe JDBC URL to connect to. The source-specific connection properties may be specified in the URL. e.g., jdbc:postgresql://localhost/test?user=fred&password=secret
dbtableThe JDBC table that should be read from or written into. Note that when using it in the read path anything that is valid in a FROM clause of a SQL query can be used. For example, instead of a full table you could also use a subquery in parentheses. It is not allowed to specify dbtable and query options at the same time.
queryA query that will be used to read data into Spark. The specified query will be parenthesized and used as a subquery in the FROM clause. Spark will also assign an alias to the subquery clause. As an example, spark will issue a query of the following form to the JDBC Source. \n \nSELECT <columns> FROM (<user_specified_query>) spark_gen_alias \n \nBelow are a couple of restrictions while using this option. \n \n1. It is not allowed to specify dbtable and query options at the same time.\n2. It is not allowed to specify query and \n partitionColumn options at the same time. When \n specifying partitionColumn option is required, the \n subquery can be specified using dbtable option \n instead and partition columns can be qualified using \n the subquery alias provided as part of dbtable.Example: \nspark.read.format(\"jdbc\")\n.option(\"url\", jdbcUrl)\n.option(\"query\", \"select c1, c2 from t1\")\n.load()
driverThe class name of the JDBC driver to use to connect to this URL.
partitionColumn, lowerBound, upperBoundThese options must all be specified if any of them is specified. In addition, numPartitions must be specified. They describe how to partition the table when reading in parallel from multiple workers. partitionColumn must be a numeric, date, or timestamp column from the table in question. Notice that lowerBound and upperBound are just used to decide the partition stride, not for filtering the rows in table. So all rows in the table will be partitioned and returned. This option applies only to reading.
numPartitionsThe maximum number of partitions that can be used for parallelism in table reading and writing. This also determines the maximum number of concurrent JDBC connections. If the number of partitions to write exceeds this limit, we decrease it to this limit by calling coalesce(numPartitions) before writing.
queryTimeoutThe number of seconds the driver will wait for a Statement object to execute to the given number of seconds. Zero means there is no limit. In the write path, this option depends on how JDBC drivers implement the API setQueryTimeout, e.g., the h2 JDBC driver checks the timeout of each query instead of an entire JDBC batch. It defaults to 0.
fetchsizeThe JDBC fetch size, which determines how many rows to fetch per round trip. This can help performance on JDBC drivers which default to low fetch size (e.g. Oracle with 10 rows). This option applies only to reading.
batchsizeThe JDBC batch size, which determines how many rows to insert per round trip. This can help performance on JDBC drivers. This option applies only to writing. It defaults to 1000.
isolationLevelThe transaction isolation level, which applies to current connection. It can be one of NONE, READ_COMMITTED, READ_UNCOMMITTED, REPEATABLE_READ, or SERIALIZABLE, corresponding to standard transaction isolation levels defined by JDBC's Connection object, with default of READ_UNCOMMITTED. This option applies only to writing. Please refer the documentation in java.sql.Connection.
sessionInitStatementAfter each database session is opened to the remote DB and before starting to read data, this option executes a custom SQL statement (or a PL/SQL block). Use this to implement session initialization code. Example: option(\"sessionInitStatement\", \"\"\"BEGIN execute immediate 'alter session set \"_serial_direct_read\"=true'; END;\"\"\")
truncateThis is a JDBC writer related option. When SaveMode.Overwrite is enabled, this option causes Spark to truncate an existing table instead of dropping and recreating it. This can be more efficient, and prevents the table metadata (e.g., indices) from being removed. However, it will not work in some cases, such as when the new data has a different schema. It defaults to false. This option applies only to writing.
cascadeTruncateThis is a JDBC writer related option. If enabled and supported by the JDBC database (PostgreSQL and Oracle at the moment), this options allows execution of a TRUNCATE TABLE t CASCADE (in the case of PostgreSQL a TRUNCATE TABLE ONLY t CASCADE is executed to prevent inadvertently truncating descendant tables). This will affect other tables, and thus should be used with care. This option applies only to writing. It defaults to the default cascading truncate behaviour of the JDBC database in question, specified in the isCascadeTruncate in each JDBCDialect.
createTableOptionsThis is a JDBC writer related option. If specified, this option allows setting of database-specific table and partition options when creating a table (e.g., CREATE TABLE t (name string) ENGINE=InnoDB.). This option applies only to writing.
createTableColumnTypesThe database column data types to use instead of the defaults, when creating the table. Data type information should be specified in the same format as CREATE TABLE columns syntax (e.g: \"name CHAR(64), comments VARCHAR(1024)\"). The specified types should be valid spark sql data types. This option applies only to writing.
customSchemaThe custom schema to use for reading data from JDBC connectors. For example, \"id DECIMAL(38, 0), name STRING\". You can also specify partial fields, and the others use the default type mapping. For example, \"id DECIMAL(38, 0)\". The column names should be identical to the corresponding column names of JDBC table. Users can specify the corresponding data types of Spark SQL instead of using the defaults. This option applies only to reading.
pushDownPredicateThe option to enable or disable predicate push-down into the JDBC data source. The default value is true, in which case Spark will push down filters to the JDBC data source as much as possible. Otherwise, if set to false, no filter will be pushed down to the JDBC data source and thus all filters will be handled by Spark. Predicate push-down is usually turned off when the predicate filtering is performed faster by Spark than by the JDBC data source.

MySQL Example

-- Creating a proxy table
CREATE TABLE mysqlTable
USING org.apache.spark.sql.jdbc
OPTIONS (
url "jdbc:mysql://db_host:db_port/db_name",
dbtable "schema.tablename",
driver 'com.mysql.cj.jdbc.Driver',
user 'username',
password 'password'
);

-- Reading from proxy table
SELECT * FROM mysqlTable;

-- Writing to mysql
INSERT INTO TABLE mysqlTable
SELECT * FROM dwhTable;

PostgreSQL Example

-- Creating a proxy view
CREATE TABLE postgreTable
USING org.apache.spark.sql.jdbc
OPTIONS (
url "jdbc:postgresql://db_host:db_port/db_name",
dbtable 'schema.tablename',
user 'username',
password 'password'
);

-- Reading from proxy view
SELECT * FROM postgreTable;

-- Writing to mysql
INSERT INTO TABLE postgreTable
SELECT * FROM dwhTable;