mssql-python 驱动程序支持 Microsoft SQL 的 binary、varbinary 和 image 数据类型。
Microsoft SQL 在以下列类型中存储二进制数据:
| 类型 | 描述 | 最大大小 |
|---|---|---|
binary(n) |
固定长度的二进制数据。 | 8000字节 |
varbinary(n) |
可变长度二进制数据。 | 8000字节 |
varbinary(max) |
大型二进制数据。 | 2 GB |
image |
遗留的大二进制数据(已弃用)。 | 2 GB |
mssql-python 驱动以 Python bytes 对象的形式返回二进制数据。
何时将二进制存储在数据库中,何时存储在文件系统中:
- 当文件较小(低于 1 MB)、需要与其他数据保持事务一致性,或者需要将数据和文件一起备份时,应将文件存储在数据库中。
- 当文件体积大(超过1MB)、需要CDN传输,或者需要直接向客户端提供文件且无需数据库往返时,存储在文件系统(或Azure Blob 存储)中。
- 作为折中方案,Microsoft SQL 的 FILESTREAM 功能将数据存储在文件系统中,同时保持事务一致性。
插入二进制数据
将 Python bytes 对象作为参数传递;驱动程序将其映射到 varbinary 列。
直接插入字节
创建一个 Python bytes 对象,并将其作为查询参数传递:
import mssql_python
conn = mssql_python.connect(connection_string)
cursor = conn.cursor()
# Create a table to hold binary documents
cursor.execute("""
CREATE TABLE #Documents (
ID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(255),
Content VARBINARY(MAX),
Size INT NULL,
ContentHash VARBINARY(32) NULL
)
""")
# Binary data as bytes
binary_data = b'\x00\x01\x02\x03\x04\x05'
cursor.execute(
"INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
{"name": "sample.bin", "content": binary_data}
)
conn.commit()
从文件插入
以二进制模式读取文件并插入其内容:
def insert_file(cursor, file_path: str, name: str):
"""Insert a file as binary data."""
with open(file_path, "rb") as f:
content = f.read()
cursor.execute(
"INSERT INTO #Documents (Name, Content, Size) VALUES (%(name)s, %(content)s, %(size)s)",
{"name": name, "content": content, "size": len(content)}
)
insert_file(cursor, "image.png", "profile_picture.png")
conn.commit()
插入图像文件
通过通过文件扩展名检测MIME类型来存储包含元数据的图像文件:
# Create a table to hold images
cursor.execute("""
CREATE TABLE #Images (
ID INT IDENTITY PRIMARY KEY,
FileName NVARCHAR(255),
FileSize INT NULL,
ContentType NVARCHAR(100) NULL,
Width INT NULL,
Height INT NULL,
ImageData VARBINARY(MAX),
Description NVARCHAR(MAX) NULL
)
""")
def insert_image(cursor, image_path: str, description: str):
"""Insert an image into the database."""
import os
with open(image_path, "rb") as f:
image_data = f.read()
cursor.execute("""
INSERT INTO #Images (FileName, FileSize, ContentType, ImageData, Description)
VALUES (%(filename)s, %(filesize)s, %(content_type)s, %(data)s, %(desc)s)
""", {
"filename": os.path.basename(image_path),
"filesize": len(image_data),
"content_type": get_content_type(image_path),
"data": image_data,
"desc": description
})
def get_content_type(path: str) -> str:
"""Determine MIME type from file extension."""
ext = path.lower().split(".")[-1]
types = {
"png": "image/png",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"gif": "image/gif",
"pdf": "application/pdf",
}
return types.get(ext, "application/octet-stream")
检索二进制数据
驱动程序将 varbinary 和 binary 列值作为 Python bytes 对象返回。
提取二进制列
查询二进制列并检查返回 bytes 的对象:
cursor.execute(
"SELECT LargePhotoFileName, LargePhoto FROM Production.ProductPhoto WHERE ProductPhotoID = %(id)s",
{"id": 70}
)
row = cursor.fetchone()
# LargePhoto is bytes
print(type(row.LargePhoto)) # <class 'bytes'>
print(len(row.LargePhoto)) # Number of bytes
保存到文件
检索二进制数据并写入磁盘:
def save_photo(cursor, photo_id: int, output_path: str):
"""Retrieve binary data and save to file."""
cursor.execute(
"SELECT LargePhoto FROM Production.ProductPhoto WHERE ProductPhotoID = %(id)s",
{"id": photo_id}
)
row = cursor.fetchone()
if row and row.LargePhoto:
with open(output_path, "wb") as f:
f.write(row.LargePhoto)
print(f"Saved {len(row.LargePhoto)} bytes to {output_path}")
else:
print("Photo not found or empty")
save_photo(cursor, 70, "output.gif")
导出二进制行到文件
将多行二进制数据导出到本地文件:
import os
def export_photos(cursor, output_dir: str):
"""Export product photos to a directory."""
os.makedirs(output_dir, exist_ok=True)
cursor.execute("""
SELECT ProductPhotoID, LargePhotoFileName, LargePhoto
FROM Production.ProductPhoto
WHERE ProductPhotoID > 1
""")
count = 0
for row in cursor:
output_path = os.path.join(output_dir, f"{row.ProductPhotoID}_{row.LargePhotoFileName}")
with open(output_path, "wb") as f:
f.write(row.LargePhoto)
count += 1
print(f"Exported {count} photos to {output_dir}")
export_photos(cursor, "./photos")
插入空二进制值
传入 None 以在二进制列中插入 SQL NULL。 由于 #Documents 是临时表,请先使用 setinputsizes() 声明参数类型,以便驱动程序将 Content 绑定为 varbinary:
cursor.setinputsizes([(mssql_python.SQL_WVARCHAR, 255, 0), (mssql_python.SQL_VARBINARY, 0, 0)])
cursor.execute(
"INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
{"name": "empty", "content": None}
)
注释
驱动程序通常通过 SQLDescribeParam推断参数类型,但无法解析 临时表 或 表变量的类型元数据。 将 None 插入临时对象的 binary 或 varbinary 列且未使用 setinputsizes() 时,会引发 ProgrammingError: Implicit conversion from data type varchar to varbinary(max) is not allowed。 按顺序为每个参数传递一个条目,并对二进制列使用诸如 mssql_python.SQL_VARBINARY 之类的 SQL 类型常量。 对于普通(永久)表,驱动会自动解析类型,你可以直接传递 None 。
大型二进制数据
对于超过几兆字节的文件,应通过一次varbinary(max)写入插入全部内容,而不是以小块方式读取文件。
流式传输大文件
对于大文件,按分块处理:
def insert_large_file(conn, table: str, file_path: str, chunk_size: int = 8192):
"""Insert large file in chunks using updatetext-style approach."""
# Validate table name to prevent SQL injection
import re
if not re.match(r'^#{0,2}[A-Za-z_][A-Za-z0-9_.]*$', table):
raise ValueError(f"Invalid table name: {table}")
cursor = conn.cursor()
# Get file size
import os
file_size = os.path.getsize(file_path)
# Insert initial row with empty binary
cursor.execute(f"""
INSERT INTO {table} (Name, Content, Size)
VALUES (%(name)s, 0x, %(size)s);
SELECT SCOPE_IDENTITY();
""", {"name": os.path.basename(file_path), "size": file_size})
row_id = cursor.fetchval()
# For modern Microsoft SQL, better to use varbinary(max) and single insert
# This example shows streaming approach
with open(file_path, "rb") as f:
content = f.read()
cursor.execute(f"""
UPDATE {table} SET Content = %(content)s WHERE ID = %(id)s
""", {"content": content, "id": row_id})
conn.commit()
return row_id
使用批量副本来存储二进制数据
使用该 bulkcopy() 方法在一次操作中高效插入多个二进制文件。
Important
bulkcopy() 通过与服务器的 单独连接 加载数据,因此目标表必须已存在,并且 已提交且对其他会话可见。 如果你在同一脚本中创建表并关闭了自动提交,请先调用 conn.commit(),再调用 bulkcopy()。 本地临时表(#name)不受支持,因为它们仅对创建它们的会话可见。 未提交的或无法到达的目的地会导致 bulkcopy() 因 Failed to retrieve destination metadata 超时而失败。
默认情况下, bulkcopy() 行中的每个值按序数位置映射到表列,因此每列必须有顺序的值。 当表有身份列或只填充部分列时,明确传入 column_mappings 目标列名。 否则数值会移到错误的列,导致 bulkcopy() 失败。
def bulk_insert_files(conn, table: str, file_paths: list[str]):
"""Bulk insert multiple binary files."""
import os
data = []
for path in file_paths:
with open(path, "rb") as f:
content = f.read()
data.append((os.path.basename(path), content, len(content)))
cursor = conn.cursor()
result = cursor.bulkcopy(table, data, column_mappings=["Name", "Content", "Size"])
conn.commit()
return result["rows_copied"]
二进制数据操作
使用Microsoft SQL函数HASHBYTES比较二进制内容,无需获取完整值。
比较二进制数据
通过计算和比较 Microsoft SQL Server 中的内容哈希,找到共享相同内容的二进制行:
# Find rows with identical binary content by hash
cursor.execute("""
SELECT LargePhotoFileName, HASHBYTES('SHA2_256', LargePhoto) AS PhotoHash
FROM Production.ProductPhoto
WHERE ProductPhotoID > 1
""")
hashes = {}
for row in cursor:
hash_value = row.PhotoHash # bytes
if hash_value in hashes:
print(f"Duplicate: {row.LargePhotoFileName} matches {hashes[hash_value]}")
else:
hashes[hash_value] = row.LargePhotoFileName
在 Python 中计算哈希
用 Python 计算 SHA-256 哈希值,并将其与二进制数据一起存储:
import hashlib
def insert_with_hash(cursor, name: str, content: bytes):
"""Insert binary data with computed hash."""
content_hash = hashlib.sha256(content).digest()
cursor.execute("""
INSERT INTO #Documents (Name, Content, ContentHash)
VALUES (%(name)s, %(content)s, %(hash)s)
""", {"name": name, "content": content, "hash": content_hash})
编码和解码二进制数据
将二进制数据转换为 Base64 编码字符串,或从 Base64 编码字符串转换为二进制数据:
import base64
# Store base64-encoded string
def insert_base64(cursor, name: str, base64_data: str):
"""Insert base64-encoded data as binary."""
binary_data = base64.b64decode(base64_data)
cursor.execute(
"INSERT INTO #Documents (Name, Content) VALUES (%(name)s, %(content)s)",
{"name": name, "content": binary_data}
)
# Retrieve as base64
def get_as_base64(cursor, doc_id: int) -> str:
"""Retrieve binary data as base64 string."""
cursor.execute("SELECT Content FROM #Documents WHERE ID = %(id)s", {"id": doc_id})
row = cursor.fetchone()
return base64.b64encode(row.Content).decode("utf-8")
处理特定二进制格式
这些示例展示了如何在存储前验证和插入常见文件格式。
PDF 文档
插入前请核实PDF文件签名:
def insert_pdf(cursor, pdf_path: str, title: str):
"""Insert a PDF document."""
with open(pdf_path, "rb") as f:
pdf_data = f.read()
# Verify it's a PDF (magic bytes)
if not pdf_data.startswith(b'%PDF'):
raise ValueError("Not a valid PDF file")
cursor.execute(
"INSERT INTO #Documents (Name, Content) VALUES (%(title)s, %(data)s)",
{"title": title, "data": pdf_data}
)
带有PIL/Pillow的图片
在存储图片前使用Pillow(PIL)调整大小以节省空间:
from PIL import Image
import io
import os
def insert_resized_image(cursor, image_path: str, max_size: tuple = (800, 600)):
"""Insert a resized image."""
# Open and resize
img = Image.open(image_path)
img.thumbnail(max_size, Image.LANCZOS)
# Convert to bytes
buffer = io.BytesIO()
img.save(buffer, format=img.format or "PNG")
image_bytes = buffer.getvalue()
cursor.execute("""
INSERT INTO #Images (FileName, Width, Height, ImageData)
VALUES (%(name)s, %(width)s, %(height)s, %(data)s)
""", {
"name": os.path.basename(image_path),
"width": img.width,
"height": img.height,
"data": image_bytes
})
def get_image_as_pil(cursor, image_id: int) -> Image.Image:
"""Retrieve image as PIL Image object."""
cursor.execute("SELECT ImageData FROM #Images WHERE ID = %(id)s", {"id": image_id})
row = cursor.fetchone()
return Image.open(io.BytesIO(row.ImageData))
压缩数据
通过插入前用 gzip 压缩二进制数据来减少存储空间:
import gzip
def insert_compressed(cursor, name: str, data: bytes):
"""Insert data with gzip compression."""
compressed = gzip.compress(data)
cursor.execute(
"INSERT INTO #Documents (Name, Content, Size) VALUES (%(name)s, %(content)s, %(size)s)",
{"name": name, "content": compressed, "size": len(data)}
)
def get_decompressed(cursor, data_id: int) -> bytes:
"""Retrieve and decompress data."""
cursor.execute(
"SELECT Content FROM #Documents WHERE ID = %(id)s",
{"id": data_id}
)
row = cursor.fetchone()
return gzip.decompress(row.Content)
最佳做法
应用这些指南,为二进制数据选择合适的列类型和存储策略。
使用合适的柱类型
根据数据特性选择列类型:
对于不同的二进制用例,请选择合适的 Microsoft SQL 数据类型:
-- For small fixed-size binary (for example, hashes, UUIDs)
binary(32) -- SHA-256 hash
-- For variable-size binary up to 8KB (for example, thumbnails, small icons)
varbinary(8000)
-- For large binary data (for example, documents, images)
varbinary(max) -- Up to 2GB
对于大型文件,可考虑使用 FILESTREAM
对于大文件(超过1 MB),可以考虑Microsoft的SQL FILESTREAM功能,该功能将数据存储在文件系统中。 FILESTREAM 在使用前需要 服务器端配置 :
# FILESTREAM-enabled databases store large binaries more efficiently
# Access is still through normal queries but storage is file-based
large_binary_data = b"\x25\x50\x44\x46" + b"\x00" * 100 # sample data
cursor.execute("""
CREATE TABLE ##FileStreamDemo (Name NVARCHAR(100), Document VARBINARY(MAX))
""")
cursor.execute("""
INSERT INTO ##FileStreamDemo (Name, Document)
VALUES (%(name)s, %(content)s)
""", {"name": "large_doc.pdf", "content": large_binary_data})
cursor.execute("SELECT Name, DATALENGTH(Document) AS DocSize FROM ##FileStreamDemo")
row = cursor.fetchone()
print(f"{row.Name}: {row.DocSize} bytes")
验证二进制数据
在存储二进制数据前,通过检查魔字节(文件签名)来验证文件类型:
def insert_safe_image(cursor, name: str, data: bytes):
"""Insert image with validation."""
# Check file signatures (magic bytes)
signatures = {
b'\x89PNG': 'image/png',
b'\xff\xd8\xff': 'image/jpeg',
b'GIF87a': 'image/gif',
b'GIF89a': 'image/gif',
}
content_type = None
for sig, mime in signatures.items():
if data.startswith(sig):
content_type = mime
break
if content_type is None:
raise ValueError("Unknown or unsupported image format")
cursor.execute("""
INSERT INTO #Images (FileName, ContentType, ImageData)
VALUES (%(name)s, %(type)s, %(data)s)
""", {"name": name, "type": content_type, "data": data})