首页 > 解决方案 > 为什么我的代码无法使用 python 和 SQL 服务器将字符串转换为字节

问题描述

几个小时以来,我一直试图将我的 python 文件图像保存到我的数据库表中,但由于转换问题并出现以下错误通知而无济于事:

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. 

photo 表列的数据类型为 varbinary(max)。我在这里进行了研究,发现了成员的类似帖子和评论,但没有一个可以帮助解决我的问题。

如何在 python 中将字符串值转换为字节以使我能够将记录保存在数据库中?我试图使用字节(文件名),它没有用。我也试过:

  base64.encodebytes(filename)

我在导入base64之后这样做了,它仍然没有工作。然后我尝试了:

 base(filename,'ascii')

它仍然没有工作。

我想要一种情况,当我从对话框上传照片并将其附加到文件中时,上传的照片可以保存在数据库表中为其保留的列中,并且该列的数据类型为 varbinary(max)。以下是我的代码:

        try:
        fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
        strfn = bytes(fname,'ascii')
        self.pixL.setPixmap(QPixmap(fname).scaled(250, 250))
        self.pixTx.setText(fname)
        self.pixL.setText(strfn)
    except Exception as err:
     print(err)

这是插入语句:

             self.cursor.execute(
            "INSERT INTO pixx1(photop, photopath)"
            "VALUES(?,?)",
            #the parameter placholder for pyodbc is the question mark sign (?), whereas that of MySql is %s
            (self.pixL.text(),
             self.pixTx.text())

标签: pythonsqldatabasepyqt5varbinary

解决方案


经过近 10 个小时的深入研究和批判性思考,我终于能够解决它。错误说

  "implicit conversion from data type nvarchar to varbinary(max) 
  is not allowed. use the convert function to run this query."

我尝试了我得到的所有建议,但 Microsoft SQL 拒绝了它们,坚持不能隐式完成转换,我的理解是我或用户必须在 SQL 服务器中进行转换并使用转换或铸造。

我决定重新创建一个表来测试照片上传。该表仅给出 2 列,

   CREATE table pixx2(
        photopath varchar(500),
        photo-p AS CAST(photopath AS varbinary(max))
       )

插入语句是:

           insert into pixx2(photopath) value(?),
           (self.pixTx.text())

pixTx 是上传照片的文件路径文本(字符串值),存入数据库时​​会触发 photo-p 列接收副本并保存在 varbinary 中。

我已经达到了我想要的。谢谢。


推荐阅读