0

I tried using the py4j referred Connecting and testing a JDBC driver from Python

from py4j.JavaGateway import java_gateway

# Open JVM interface with the JDBC Jar
jdbc_jar_path = 'C:\Program Files\CData\CData JDBC Driver for MongoDB 2019\lib\cdata.jdbc.mongodb.jar'
gateway = java_gateway(classpath=jdbc_jar_path) 

# Load the JDBC Jar
jdbc_class = "cdata.jdbc.mongodb.MongoDBDriver"
gateway.jvm.class.forName(jdbc_class)

# Initiate connection
jdbc_uri = "jdbc:mongodb:Server=127.0.0.1;Port=27017;Database=EmployeeDB;"
con =  gateway.jvm.DriverManager.getConnection(jdbc_uri)

# Run a query
sql = "select * from Employees"
stmt = con.createStatement(sql)
rs = stmt.executeQuery()
while rs.next():
    rs.getInt(1)
    rs.getFloat(2)
    .
    .
rs.close()
stmt.close()

Getting error as

 File "assignment.py", line 9
    gateway.jvm.class.forName(jdbc_class)
                ^
SyntaxError: invalid syntax
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104

1 Answers1

0

Try replacing

gateway.jvm.class.forName(jdbc_class)

with

gateway.jvm.Class.forName(jdbc_class)

(i.e. capitalise the c in class.)

Class.forName is the Java method you want to call here. (Note also how the D in DriverManager is capitalised in gateway.jvm.DriverManager.getConnection(...).) However, the syntax error is caused because class is a Python keyword. You can't have a local variable, or a function or method, named class.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • Now getting below error Traceback (most recent call last): File "assignment.py", line 1, in from py4j.JavaGateway import java_gateway ModuleNotFoundError: No module named 'py4j.JavaGateway' – Karan Punjabi Dec 16 '19 at 15:14
  • Looks like you haven't installed py4j: https://www.py4j.org/install.html . – Luke Woodward Dec 16 '19 at 21:53