我使用 JDBC 在 python 中使用 JayDeBeApi 连接到 MySql:
def data_JDBC(db_name, table, db, user, pwd):
db = db.lower()
db_name = db_name.lower()
print(db)
if db == 'postgresql':
sql_str = f"select * from {db}.{table}"
host='ec2-18-191-149-107.us-east-2.compute.amazonaws.com'
port='5432'
user=user
pwd = pwd
driver_name = 'org.postgresql.Driver'
driver_path = 'path/to/postgresql-42.2.12.jar'
elif db == 'mysql':
sql_str = f"select * from {table}"
host='localhost'
port='3306'
user=user
pwd = ""
driver_name = 'com.mysql.cj.jdbc.Driver'
driver_path = 'path/to/mysql-connector-java-8.0.20.jar'
print(driver_path)
connection_string=f'jdbc:{db}://'+ host+':'+ port +'/'+ db_name+'?useSSL=false&&serverTimezone=UTC&useLegacyDatetimeCode=false'
if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
jpype.java.lang.Thread.currentThread().setContextClassLoader(jpype.java.lang.ClassLoader.getSystemClassLoader())
conn = jaydebeapi.connect(driver_name, connection_string,[user, pwd], jars=driver_path)
frame = pd.read_sql(sql_str, conn);
pd.set_option('display.expand_frame_repr', False)
conn.close()
return frame
这个函数返回一个 Pandas DataFrame,我在同一目录中有 jar 文件。PostgreSQL 工作正常,但是当我选择 MySQL 时出现此错误:
java.lang.RuntimeExceptionPyRaisable Traceback (most recent call last)
<ipython-input-426-311d4ecabc53> in <module>
----> 1 dfMysql=data_JDBC(db_name='fuentedatos', table='tests', db='MySql', user='root', pwd='')
2 dfMysql
...
java.lang.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class com.mysql.cj.jdbc.Driver not found
这就是我执行该功能的方式:
data_JDBC(db_name='fuentedatos', table='tests', db='MySql', user='root', pwd='')