【问题标题】:parameter is not valid when loading image from database after updating the image with text on it in c#在 c# 中更新带有文本的图像后从数据库加载图像时参数无效
【发布时间】:2016-09-08 19:20:52
【问题描述】:

我有一个学生表,其中一个图像字段是学生 ID,通过将学生信息放在 png 文件中创建的学生 ID 并保存在数据库中 这是将文本放在图像文件上并将其保存在数据库中的代码,它可以正常工作

byte[] pic=null;
//call the idcard image
    Bitmap bitMapImage = new System.Drawing.Bitmap(@"C:\Users\pary\Videos\login2\login\image\card.png");
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString(TxtNamestudent.Text,
  new Font("Arial", 10),
        SystemBrushes.WindowText, new Point(1500, 555));
graphicImage.DrawString(comdep.SelectedItem.ToString(),
   new Font("Arial", 10),
        SystemBrushes.WindowText, new Point(1550, 690));
graphicImage.DrawString(dateTimePicker1.Value.ToString("MM/dd/yyyy"),
   new Font("Arial", 10),
       SystemBrushes.WindowText, new Point(1250, 850));
graphicImage.DrawString(cmbBloodgroup.SelectedItem.ToString(),
   new Font("Arial", 10),
      SystemBrushes.WindowText, new Point(1780, 960));
graphicImage.DrawString(dateTimePicker2.Value.ToString("MM/dd/yyyy"),
   new Font("Arial", 10),
        SystemBrushes.WindowText, new Point(1300, 1100));
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
// if (open.ShowDialog() == DialogResult.OK)
//{
// display image in picture box
//  Image secondimage = new Bitmap(open.FileName);
// Image bimap2 = ResizeImage(secondimage, 70, 100);
//Bitmap bimap2 = new Bitmap(secondimage, new Size(12, 15));
using (Graphics g = Graphics.FromImage(bitMapImage))
{
    //draw other image on top of main Image
    g.DrawImage(bimap2, new Point(170, 600));
     final = ResizeImage(bitMapImage, 500, 400);
    //save new image
     final.Save(@"C:\Users\pary\Videos\login2\login\image" + TxtNamestudent.Text + ".Jpg");
    pictureBox2.Image = final;
    pictureBox2.Height = final.Height;
    pictureBox2.Width = final.Width;
    imglocation = (@"C:\Users\pary\Videos\login2\login\image" + TxtNamestudent.Text + ".Jpg");
    FileStream fs = new FileStream(imglocation, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    pic = br.ReadBytes((int)fs.Length);
    //MemoryStream stream = new MemoryStream();
    //pic = stream.ToArray();

}

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\pary\Videos\login2\login\Database1.mdf;Integrated Security=True;User Instance=True");
//open the connetion
con.Open();
//write query

SqlCommand cmd = new SqlCommand(@"INSERT INTO Table4 (KurdName,EnglishName,Blood,Gender,Sale_Ladaekbwn,Sale_Darchun,PhoneNumber,Email,Qonax,Schul,Department,pic)
VALUES (N'" + TxtNamestudent.Text + "','" + Txtname.Text + "','" + cmbBloodgroup.SelectedItem.ToString() + "',N'" + Gender + "','" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "','" + dateTimePicker2.Value.ToString("MM/dd/yyyy") + "','" + textmobil.Text + "','" + TxtEmail.Text + "',N'" + combqonax.SelectedItem.ToString() + "',N'" + comskul.SelectedItem.ToString() + "',N'" + comdep.SelectedItem.ToString() + "', @pic )", con);
cmd.Parameters.AddWithValue("@pic", pic);
cmd.ExecuteNonQuery();
con.Close();

这是加载图像并将其放在图片框上的代码,它也可以正常工作

string date_birth = (myreader["Sale_Ladaekbwn"].ToString());
string date_issue = (myreader["Sale_Darchun"].ToString());
DateTime date1 = DateTime.Parse(date_birth);
DateTime date2 = DateTime.Parse(date_issue);
dateTimePicker1.Value = date1;
dateTimePicker2.Value = date2;
byte[] data = new byte[0];
data = (Byte[])(myreader["pic"]);

MemoryStream mem = new MemoryStream(data);
//mem.Seek(0, SeekOrigin.Begin);
// Bitmap img = (Bitmap)System.Drawing.Image.FromStream(mem);
mem.Write(data, 0, data.Length);
mem.Position = 0;
Bitmap bmp = new Bitmap(mem);
pictureBox2.Image= Image.FromStream(mem);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
mem.Close();

上面的代码正在运行,它正在从数据库中加载图像并将其放入图片框中

我遇到的问题是当我尝试更新存储在数据库中的图像和信息时,这是更新数据库中 id 图像的代码

private void btn_update_Click(object sender, EventArgs e)
{

    byte[] pic = null;
    //call the idcard image
    Bitmap bitMapImage = new System.Drawing.Bitmap(@"C:\Users\pary\Videos\login2\login\image\card.png");
    Graphics graphicImage = Graphics.FromImage(bitMapImage);
    graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
    graphicImage.DrawString(TxtNamestudent.Text,
       new Font("Arial", 10),
             SystemBrushes.WindowText, new Point(1450, 555));
    graphicImage.DrawString(comdep.SelectedItem.ToString(),
        new Font("Arial", 10),
             SystemBrushes.WindowText, new Point(1550, 690));
    graphicImage.DrawString(dateTimePicker1.Value.ToString("MM/dd/yyyy"),
       new Font("Arial", 10),
           SystemBrushes.WindowText, new Point(1200, 850));
    graphicImage.DrawString(cmbBloodgroup.SelectedItem.ToString(),
       new Font("Arial", 10),
          SystemBrushes.WindowText, new Point(1780, 960));
    graphicImage.DrawString(dateTimePicker2.Value.ToString("MM/dd/yyyy"),
        new Font("Arial", 10),
             SystemBrushes.WindowText, new Point(1300, 1100));
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
    // if (open.ShowDialog() == DialogResult.OK)
    //{
    // display image in picture box
    //  Image secondimage = new Bitmap(open.FileName);
    // Image bimap2 = ResizeImage(secondimage, 70, 100);
    //Bitmap bimap2 = new Bitmap(secondimage, new Size(12, 15));
    using (Graphics g = Graphics.FromImage(bitMapImage))
    {
        //draw other image on top of main Image
        g.DrawImage(bimap2, new Point(170, 600));
        final = ResizeImage(bitMapImage, 500, 400);
        //save new image
        final.Save(@"C:\Users\pary\Videos\login2\login\image"+ TxtNamestudent.Text + ".Jpg");
        pictureBox2.Image = final;
        pictureBox2.Height = final.Height;
        pictureBox2.Width = final.Width;
        imglocation = (@"C:\Users\pary\Videos\login2\login\image" + TxtNamestudent.Text + ".Jpg");
        FileStream fs = new FileStream(imglocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        pic = br.ReadBytes((int)fs.Length);
        //MemoryStream stream = new MemoryStream();
        //pic = stream.ToArray();
    }




    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\pary\Videos\login2\login\Database1.mdf;Integrated Security=True;User Instance=True");
    con.Open();
    SqlCommand cmd = new SqlCommand(@"update Table4 set KurdName=
          N'" + TxtNamestudent.Text + "',EnglishName='" + Txtname.Text + "',Blood='" + cmbBloodgroup.SelectedItem.ToString() + "',Gender=N'" + Gender + "',Sale_Ladaekbwn='" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "',Sale_Darchun='" + dateTimePicker2.Value.ToString("MM/dd/yyyy") + "',PhoneNumber='" + textmobil.Text + "',Email='" + TxtEmail.Text + "',Qonax=N'" + combqonax.SelectedItem.ToString() + "',Schul=N'" + comskul.SelectedItem.ToString() + "',Department=N'" + comdep.SelectedItem.ToString() + "',pic='" + pic + "'  where( ID='" + numVal + "')", con);
    cmd.Parameters.AddWithValue("@pic", pic);
    cmd.ExecuteNonQuery();
    con.Close();

此代码正在更新 id 图像上的信息并保存它。出现问题我试图在更新后加载图像,它给了我“参数无效”异常。我使用相同的代码来加载图像。

string date_birth = (myreader["Sale_Ladaekbwn"].ToString());
string date_issue = (myreader["Sale_Darchun"].ToString());
DateTime date1 = DateTime.Parse(date_birth);
DateTime date2 = DateTime.Parse(date_issue);
dateTimePicker1.Value = date1;
dateTimePicker2.Value = date2;
byte[] data = new byte[0];
data = (Byte[])(myreader["pic"]);

MemoryStream mem = new MemoryStream(data);
mem.Write(data, 0, data.Length);
mem.Position = 0;
Bitmap bmp = new Bitmap(mem);
pictureBox2.Image= Image.FromStream(mem);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
mem.Close();

它在“Bitmap bmp= new Bitmap(mem);”行中给了我错误

如果有人有任何想法,请告诉我我真的很感激,我下周有 viva。非常感谢。

【问题讨论】:

  • 您可能会通过使用查询参数而不是尝试像那样手动构建查询来使整个问题变得毫无意义。 ADO .NET 应该能够处理 byte[] 作为二进制列的参数。作为一个额外的好处,您可以防止 SQL 注入,您当前的代码是 完全开放的
  • David 谢谢,我的 C# 不太好,我能做的,你能帮忙解决吗,谢谢你的帮助。
  • MSDN 有一些关于这个主题的有用文章:msdn.microsoft.com/en-us/library/ms254953(v=vs.110).aspx
  • 您的代码非常庞大。 “new MemoryStream(data)”将已经加载流中的数据。不需要“mem.Write(..)”和“mem.Position=0”。您是否调试过代码并查看过数据的内容?
  • @JeroenHeier 谢谢,不,我没有这样做,因为我不知道该怎么做,但它给了我 Bitmap bmp=new Bitmap(mem) 行中的错误

标签: c# sql image parameters bitmap


【解决方案1】:

我假设简单的问题在这里像 "',pic='" + pic + "' 应该被纠正为 "', pic= @pic where ID='" + numVal + "'", con);

这就是它没有正确更新的原因。仔细检查您的 UPDATE 命令语法,如果它有效,请尝试..

最后,您使用的动态查询很容易受到 David 建议的 SQL 注入攻击。

因此,上述简单修正第一次应用成功后,以后最好考虑参数化查询,例如如下,
参数的 DataType 最好也具体定义。

如果您的问题解决了,请标记为答案。

SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "UPDATE Table4 SET KurdName= @k_KurdName, pic= @k_pic  WHERE Id= @k_Id";

var da = new SqlDataAdapter(comm);
da.SelectCommand.Parameters.Add(new SqlParameter("@k_KurdName", SqlDbType.NVarChar));
da.SelectCommand.Parameters["@k_KurdName"].Value = TxtNamestudent.Text;
da.SelectCommand.Parameters.Add(new SqlParameter("@k_pic", SqlDbType.Binary));
da.SelectCommand.Parameters["@k_pic"].Value = pic;
da.SelectCommand.Parameters.Add(new SqlParameter("@k_Id", SqlDbType.NVarChar));
da.SelectCommand.Parameters["@k_Id"].Value = numval;

【讨论】:

  • 我试过你的建议是它不起作用,它给了我同样的错误“参数无效”。知道是什么导致了问题吗?
  • 哦,我明白了。请试试这个。我确定这项工作! comdep.SelectedItem.ToString() + "',pic= @pic where
  • 在语法规则中,每个'"+ yourtext +"' 表示动态查询。但 不是动态查询,而是更安全的参数化查询。在 之前,它们都是动态的,但只有 部分不是动态的。我添加 只是因为 stackoverflow 不允许在评论中使用很多 @ 字符。请忽略它。您必须了解并为将来更好地更改...如果解决了,请标记为答案。我会很感激的。
  • 看看你的UPDATE命令语法,没有带@字符的参数,但你是用参数添加的。在它下面添加命令..考虑一下..
  • 我试过是一样的,你知道插入命令它工作得很好,但我不知道为什么在更新数据库中的数据后它会给我这个错误。并且更新工作正常,所有信息都正确更改。但是更新后加载图像时会出现问题。
猜你喜欢
  • 2013-11-09
  • 2012-07-10
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多