Код: Выделить всё
import jaydebeapi
class DatabaseConnection:
def __init__(self, db_host, db_port, db_database, db_user, db_password, db_driver_path, db_driver_class):
self.db_host = db_host
self.db_port = db_port
self.db_database = db_database
self.db_user = db_user
self.db_password = db_password
self.db_driver_path = db_driver_path
self.db_driver_class = db_driver_class
self.conn = None
self.cursor = None
def connect(self):
db_url = f"jdbc:db2://{self.db_host}:{self.db_port}/{self.db_database}:allowNextOnExhaustedResultSet=1;"
# print(f"db pass: {self.db_password}")
print(f"Connecting to database {self.db_database} at {self.db_host}:{self.db_port}")
try:
self.conn = jaydebeapi.connect(
self.db_driver_class,
db_url,
{'user': self.db_user, 'password': self.db_password},
self.db_driver_path
)
except Exception as e:
print(f"Error while connecting to database: {e}")
raise
if self.conn is not None:
self.conn.jconn.setAutoCommit(True)
self.cursor = self.conn.cursor()
print("Connection established.")
def execute_query(self, query, batch=100):
if not self.cursor:
raise Exception("No database connection. Please connect first.")
try:
print(f"Executing query: {query}")
self.cursor.execute(query)
count = 0
while True:
print('Inside while loop...')
rows = self.cursor.fetchmany(batch)
if not rows:
print("No more records to fetch....")
break
for record in rows:
count += 1
print(f"{count}: {record}")
except Exception as e:
print(f"Error executing query: {e}")
raise
def close(self):
try:
if self.cursor is not None:
self.cursor.close()
if self.conn is not None:
self.conn.close()
print("Connection closed.")
except Exception as e:
print(f"Error closing the connection: {e}")
raise
Код: Выделить всё
SELECT * FROM {schema}.{table};
Код: Выделить всё
Inside while loop...
.
.
batch records
.
.
Inside while loop...
.
.
batch records
.
.
Inside while loop...
Error executing query: com.ibm.db2.jcc.am.SqlException: [jcc][t4][10120][10898][4.33.31] Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null
Код: Выделить всё
db_url = f"jdbc:db2://{self.db_host}:{self.db_port}/{self.db_database}:allowNextOnExhaustedResultSet=1;"
Подробнее здесь: https://stackoverflow.com/questions/790 ... rorcode-44