简体   繁体   English

byte []到字符串未在查询中执行

[英]byte[] to String not executing in query

I have the following code. 我有以下代码。 What I am passing to the function GetInsert is the ID which then creates the INSERT Statement. 我传递给函数GetInsert的是ID,该ID然后创建了INSERT语句。 Note that _Image1 is of type byte[]. 请注意,_Image1的类型为byte []。 Image1 is of type IMAGE in the database table. Image1在数据库表中的类型为IMAGE。 Note that the way I am doing below in terms of outputting a string I am kind of stuck with as it is part of a large piece of code. 请注意,我下面在输出字符串时会做的方法,因为这是一大段代码的一部分。

    public string GetInsert(string ID)
    {

      System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();

      stringBuilder .Append("INSERT INTO tblMain(ID,Image1) VALUES (");

      stringBuilder .Append((ID) + ", ");
      stringBuilder .Append(ByteToString(_Image1) + ")");

      return stringBuilder.ToString();

    }

Because the above code needs to be converted to a string, I converted _Image1 to a string as shown below. 因为上面的代码需要转换为字符串,所以我将_Image1转换为字符串,如下所示。 Please let me know if this is the correct approach. 请让我知道这是否正确。

    public string ByteToString(byte[] bytes)
    {

        if(bytes == null)
        {

            return "NULL";

        }
      else
      {
          return "'" + System.Text.Encoding.UTF8.GetString(bytes) + "'";

      }

   }

Then elsewhere in the code I am doing the following to execute the insert statement: 然后在代码的其他地方,我正在执行以下操作来执行插入语句:

    command.CommandText = obj1.GetInsert(sID);
    command.ExecuteNonQuery();

The issue that I am running into is that when I do it as shown above the string that is converted is not in a way that is recognized when I the code tries to execute it in the ExecuteNonQuery. 我遇到的问题是,当我如上所示执行此操作时,在我的代码尝试在ExecuteNonQuery中执行它时,转换后的字符串无法以某种方式识别。 Please let me know if my approach is correct. 请让我知道我的方法是否正确。 Any suggest would be helpful 任何建议都会有所帮助

Try to use command params insted of using StringBuilder and convert byte do string. 尝试使用安装了StringBuilder的命令参数,并将字节转换为字符串。

see microsoft SqlCommand.Parameters docs 请参阅Microsoft SqlCommand.Parameters文档

Your code should be like this: 您的代码应如下所示:

command.CommandText = "INSERT INTO tblMain(ID,Image1) VALUES (@Id,@Image)";
command.Parameters.AddWithValue("@Id", sID);
command.Parameters.AddWithValue("@Image", _Image1);
command.ExecuteNonQuery();

To make it work you need to fix like this: 要使其正常工作,您需要像这样修复:

public string ByteToString(byte[] bytes)
{

    if(bytes == null)
    {

        return "NULL";

    }
  else
  {
      return "0x" + BitConverter.ToString(bytes).Replace("-", "");
  }

} }

BUT doing it this way you are asking for many troubles like sql injections. 但是这样做的话,您会遇到许多麻烦,例如sql注入。 Just use parametrized queries instead. 只需使用参数化查询即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM