Databases 3 min read

Inserting and Retrieving BLOB Data in Oracle Using Python cx_Oracle

This guide explains how to create an Oracle table with a BLOB column, insert binary files from Python using cx_Oracle by binding a BLOB variable, and later read the stored BLOB back to a file, covering all required SQL and Python code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Inserting and Retrieving BLOB Data in Oracle Using Python cx_Oracle

First, define an Oracle table that includes a BLOB column to store binary data:

CREATE TABLE aurora( date_forecast VARCHAR2(10), filename VARCHAR2(24), content BLOB );

Prepare the Python variables that hold the date, filename, and the binary content of the file you want to store:

date_forecast = '2011-06-29' filename = 'aurora.jpg' file = open('aurora.jpg', 'rb') content = file.read() file.close()

Build an INSERT statement that uses a bind variable (:blobData) for the BLOB column, and format the other values:

sqlStr = "INSERT INTO aurora (date_forecast, filename, content) VALUES ('%s', '%s', :blobData)" % (date_forecast, filename)

Tell the cursor that the bind variable blobData should be treated as a BLOB object:

cursor.setinputsizes(blobData=cx_Oracle.BLOB)

Execute the INSERT, passing the binary content as the value for blobData , and commit the transaction:

cursor.execute(sqlStr, {'blobData': content}) cursor.execute('commit')

To read the stored BLOB back, issue a SELECT that retrieves the latest row (or any row you need):

sqlStr = "SELECT date_forecast, filename, content FROM (SELECT date_forecast, filename, content FROM aurora ORDER BY date_forecast DESC) WHERE ROWNUM < 2" cursor.execute(sqlStr) result = cursor.fetchall()

The third element of the first row ( result[0][2] ) is the BLOB object. You can inspect its methods and read its data as a Python string:

print(dir(cx_Oracle.BLOB)) print(type(result[0][2].read()))

Finally, write the retrieved binary data back to a file on disk:

file = open('aurora.jpg', "wb") file.write(result[0][2].read()) file.close()

Following these steps allows seamless insertion and extraction of BLOB data between Python applications and Oracle databases using the cx_Oracle driver.

PythonSQLDatabaseOracleblobcx_Oracle
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.