This topic describes how to connect Python applications to OceanBase Database by using OceanBase Connector/J and provides sample code.
Prerequisites
A basic database development environment is deployed.
You have installed or upgraded to JDK 8 on your computer.
The Python environment on your computer is version 3.6.8.
You have obtained the installation package of the OceanBase Connector/J driver from OceanBase Technical Support.
Procedure
Install JayDeBeApi. We recommend that you install JayDeBeApi with pip. For more information, see Install JayDeBeApi with pip.
// Install JayDeBeApi of Python 3. pip3 install JayDeBeApiPlace the JAR installation package of OceanBase Connection/J in the current directory.
Establish a connection with OceanBase Database. The following sample code takes test.py as an example.
#!/usr/bin/env python3.6 # -*- coding: UTF-8 -*- encoding = "utf8" import jaydebeapi def ob_test(): url = 'jdbc:oceanbase://host:port' user = 's**@oracle' password = '**1***' driver = 'com.alipay.oceanbase.jdbc.Driver' jarFile = './oceanbase-client-2.2.3.jar' sqlStr = 'select * from test_python' # conn=jaydebeapi.connect('oracle.jdbc.driver.OracleDriver','jdbc:oracle:thin:@10.0.0.0:1521/orcl',['hwf_model','hwf_model'],'E:/pycharm/lib/ojdbc14.jar') conn = jaydebeapi.connect(driver, url, [user, password], jarFile) curs = conn.cursor() curs.execute(sqlStr) result = curs.fetchall() print(result) curs.close() conn.close() ob_test()Parameters
url:
jdbc:oceanbase://IP:port/?pool=false. Specifies the IP address and port for connecting to OceanBase Database, which is usually the IP address of an OBProxy.user: the username for connecting to the tenant, in the
username@tenant nameformat. In Oracle mode, the default username of the administrator isSYS.Note
In a private cloud or standalone deployment scenario, the format of the
usernameisString username= "username@tenant#cluster".password: specifies the password of the account.
driver: specifies the class path, which does not need to be modified.
jarFile: specifies the path of the JAR installation package.
sqlStr: specifies the SQL statement, which can be changed as needed.
After you write the script, run it. If query data is returned normally, you have connected to the database.
python3 test.py
For more information about how to use OceanBase Connector/J, see OceanBase Connector/J.