【发布时间】:2020-07-19 19:48:05
【问题描述】:
我有一个 SQL Server 数据库,其中有一个表 media 和一个类型为 varbinary(max) 的列 video。我想使用 Python 从该列中检索视频。我考虑这个question 并回答它,所以我的代码看起来像:
import pypyodbc
import base64
from base64 import *
connection = pypyodbc.connect('Driver=SQL Server;'
'Server=SQLEXPRESS;'
'Database=use_filestream_db;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
SQLCommand = ("SELECT Video FROM media")
cursor.execute(SQLCommand)
data = cursor.fetchone()[0]
data = bytes(data.strip("\n"), 'utf-8')
video_64_decode = base64.decodebytes(data)
video_result = open('landscape.mp4', 'wb')
video_result.write(video_64_decode)
video_result.close()
connection.close()
但我明白了
类型错误 回溯(最近一次通话最后一次)
在
16 cursor.execute(SQLCommand)
17 数据 = cursor.fetchone()[0]
---> 18 个数据 = 字节(data.strip("\n"), 'utf-8')
19
20 video_64_decode = base64.decodebytes(数据)TypeError: 需要一个类似字节的对象,而不是 'str'
如果我写类似
data = bytes(data.strip(bytes("\n", 'utf-8')), 'utf-8')
或者只是去掉这行输出视频会坏掉。我该如何解决?
UPD
在冻糕的回答之后,我照他说的做了,然后得到了下一个错误:
TypeError Traceback (most recent call last)
D:\programs\Anaconda\lib\base64.py in _input_type_check(s)
509 try:
--> 510 m = memoryview(s)
511 except TypeError as err:
TypeError: memoryview: a bytes-like object is required, not '_io.BytesIO'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
<ipython-input-5-40b3d6ca2642> in <module>
14 data = cursor.fetchone()[0]
15 byte_data = BytesIO(data)
---> 16 video_64_decode = base64.decodebytes(byte_data)
17
18 # USING CONTEXT MANAGER
D:\programs\Anaconda\lib\base64.py in decodebytes(s)
543 def decodebytes(s):
544 """Decode a bytestring of base-64 data into a bytes object."""
--> 545 _input_type_check(s)
546 return binascii.a2b_base64(s)
547
D:\programs\Anaconda\lib\base64.py in _input_type_check(s)
511 except TypeError as err:
512 msg = "expected bytes-like object, not %s" % s.__class__.__name__
--> 513 raise TypeError(msg) from err
514 if m.format not in ('c', 'b', 'B'):
515 msg = ("expected single byte elements, not %r from %s" %
TypeError: expected bytes-like object, not BytesIO
附:我尝试将此堆栈跟踪作为块引用发布,但它被识别为代码并返回错误。
UPD 2 我找到了解决方案,请参阅下面的答案。
【问题讨论】:
标签: python sql sql-server