如何将base64string插入varbinary类型列SQL Server

时间:2018-09-11 07:31:22

标签: sql sql-server

我有base64string(图像徽标),我想在db中插入。在数据库中,列类型为varbinary。我的查询是

update Organization set MobileLogo='gjdgfkjgk...' where orgId=1676

我收到以下错误

  

消息257,级别16,状态3,行1来自数据类型的隐式转换   不允许从varchar(max)到varbinary(max)。使用转换   函数来运行此查询。

将图片转换为base64的代码

string imagePath = @"C:\Users\arvind.ch\Downloads\Icons\SISClient_iCons\Enrich.png";
string imgBase64String = GetBase64StringForImage(imagePath);

我要在此处存储图像-

enter image description here

我需要进行SQL查询才能将其插入db而不是C#代码。上面给出的URL全部关于C#

2 个答案:

答案 0 :(得分:1)

SQL Server告诉了您一切:

  

使用CONVERT函数运行此查询。

以下是经查询的查询:

update Organization set MobileLogo=convert(varbinary(MAX),'gjdgfkjgk...') where orgId=1676

您还可以使用Convert.FromBase64String在客户端转换值:

var varbinaryData = Convert.FromBase64String("gjdgfk45vbgu");
问题更新后,

更新

要将文件读取为字节数组,请使用:

var imagePath = @"C:\Users\arvind.ch\Downloads\Icons\SISClient_iCons\Enrich.png";
var byteArray = File.ReadAllBytes(imagePath);

然后将此byteArray作为查询参数传递。

答案 1 :(得分:1)

正确回答这个问题需要做两件事:

首先,让我们回答有关如何存储对象的问题。您已经创建了一个varbinary列,因此不必理会Base64转换,因为varbinary列已经可以存储任意数据。将文件读入字节数组,然后将其发送到数据库。

其次,可能是这似乎很难做到的是,您需要参数化SQL。这有两个原因:1)首先允许您发送字节数组,2)防止SQL注入攻击,这是最容易防御的漏洞。

请考虑以下代码,这两个步骤均可完成:

using ( SqlConnection con = new SqlConnection ("your connection string"))
using ( SqlCommand com = new SqlCommand("UPDATE Organization SET MobileLogo=@FileData WHERE YourKeyColumn=@YourKeyValue", con) { CommandType = CommandType.StoredProcedure } )
{
    con.Open();
    com.Parameters.AddWithValue("@FileData", yourByteArray);
    com.Parameters.AddWithValue("@YourKeyValue", yourKeyValue);
    com.ExecuteNonQuery();
}