Quantcast
Channel: Chanmingman's Blog
Viewing all articles
Browse latest Browse all 1915

Write image file to binary field in MS SQL database Python

$
0
0

This blog article shows you how to save an image file to MS SQL database column with varbinary data type.

This Python script connects to a SQL Server database and inserts binary data from an image file into a specified table. Here’s a step-by-step explanation:

1. Import the necessary library:

The pyodbc library is used to connect to and interact with SQL databases.

2. Define database connection parameters.

These variables store the details needed to connect to the database and specify the table and column where the image data will be inserted.

3. Establish a database connection.

The pyodbc.connect function creates a connection to the database using the provided parameters. A cursor object is then created to execute SQL commands.

4. Read the image file:

The image file specified by image_path is opened in binary read mode (‘rb’). The file’s contents are read into the binary_data variable.

5. Insert the binary data into the database:

An SQL INSERT query is constructed to insert the binary data into the specified table and column. The cursor.execute method executes the query, and the conn.commit method commits the transaction to the database.

6. Print a success message:

A message is printed to indicate that the image file has been successfully written to the database.

import pyodbc

# Database connection parameters

server = ‘localhost’
database = ‘poc’
username = ‘sa’
password = ‘password’
table_name = ‘mysign’
column_name = ‘signed’
image_path = ‘image.png’

# Establish a database connection

conn = pyodbc.connect(f’DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}’)
cursor = conn.cursor()

# Read the image file

with open(image_path, ‘rb’) as file:
binary_data = file.read()

# Insert the binary data into the database

query = f”INSERT INTO {table_name} ({column_name}) VALUES (?)”
cursor.execute(query, (pyodbc.Binary(binary_data),))
conn.commit()
print(“Image file has been written to the database.”)

# Close the connection

cursor.close()
conn.close()

Also: Write image file / blob to binary field in MS SQL database

clip_image002

Source code download: https://github.com/chanmmn/python/tree/main/2024/WriteSqlBinary?WT.mc_id=DP-MVP-36769

Reference: https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver16?WT.mc_id=DP-MVP-36769


Viewing all articles
Browse latest Browse all 1915

Trending Articles