[英]Getting error after updating image in Sql server 2008 database
I am developing a winform application in VS 2010 C#. 我正在VS 2010 C#中开发Winform应用程序。 I have developed a form to insert and update the user details in this.
我已经开发了一种表单,可以在其中插入和更新用户详细信息。
My Update user form is as below image 我的更新用户表单如下图所示
![Update User Screen][1] ![更新用户屏幕] [1]
http://i.stack.imgur.com/iZaAJ.png http://i.stack.imgur.com/iZaAJ.png
And coding to update is 编码更新是
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;
namespace SampleApplication
{
public partial class UserUpdate : Form
{
public UserUpdate()
{
InitializeComponent();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection("user id=sa; password=123;initial catalog=Inventory;data source=Aniket-PC");
SqlCommand cmd;
MemoryStream ms;
byte[] photo_array;
DataSet ds;
int rno = 0;
string str;
private void nameTxt_Validating(object sender, CancelEventArgs e)
{
if (nameTxt.Text.Trim().Length == 0)
{
namewarning.Visible = true;
}
else
{
namewarning.Visible = false;
}
}
private void Update_Load(object sender, EventArgs e)
{
contTxt.MaxLength = 10;
retriveData();
retriveImg();
}
void retriveImg()
{
con.Open();
cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet("MyImage");
da.Fill(ds, "MyImage");
DataRow myRow;
myRow = ds.Tables["MyImage"].Rows[0];
photo_array = (byte[])myRow["Logo"];
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
con.Close();
}
void retriveData()
{
con.Open();
cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
nameTxt.Text = (read["Name"].ToString());
passTxt.Text = (read["Password"].ToString());
conPassTxt.Text = (read["Password"].ToString());
emailTxt.Text = (read["EmailId"].ToString());
addTxt.Text = (read["Address"].ToString());
contTxt.Text = (read["ContactNo"].ToString());
DORTxt.Text = (read["DOR"].ToString());
validity.Text = "Account Valid till "+(read["Validity"].ToString());
}
read.Close();
con.Close();
}
private void AttachBtn_Click(object sender, EventArgs e)
{
// Open image by OpenFiledialog and show it in PicturBox.
try
{
//filter only image format files.
openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openFileDialog1.ShowDialog();
if (res == DialogResult.OK)
{
Image img = new Bitmap(openFileDialog1.FileName);
//inserting image in PicturBox
profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
openFileDialog1.RestoreDirectory = true;
}
}
catch
{
MessageBox.Show("Cannot upload image");
}
}
private void UpdateBtn_Click_1(object sender, EventArgs e)
{
string DOM = dateTimePicker1.Value.ToShortDateString();
if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
{
MessageBox.Show("Please correct the marked fields");
}
else
{
//cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',@Logo,'" + DOM+ "')", con);
str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), @"Logo" ,DOM,uNameTxt.Text);
con_photo();
//con.Open();
cmd = new SqlCommand(str, con);
int count= cmd.ExecuteNonQuery();
if (count > 0)
MessageBox.Show("Sucsess");
else
MessageBox.Show("need to work");
}
}
void con_photo()
{
if (profPic.Image != null)
{
ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_array = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_array, 0, photo_array.Length);
cmd.Parameters.AddWithValue("@Logo", photo_array);
}
}
when i run the application it executes very well and shows me success message but when i again try to view the update user form it shows below screenshot error 当我运行该应用程序时,它执行得很好,并向我显示成功消息,但是当我再次尝试查看更新用户表单时,它在屏幕截图错误下方显示
http://i.stack.imgur.com/7z1Rx.png http://i.stack.imgur.com/7z1Rx.png
at retriveImg () 在retriveImg()
Please help me with resolution for this.. 请帮我解决这个问题。
You're not passing the image bytes to the UPDATE
command, but a string containing the word Logo
. 您没有将图像字节传递给
UPDATE
命令,而是将包含单词Logo
的字符串传递给了。
Also: PLEASE avoid creating SQL commands using string concatenation or String.Format
. 另外: 请避免使用字符串连接或
String.Format
创建SQL命令。 Use parameterized queries instead! 请改用参数化查询!
Also: Do not use an NVARCHAR
field to store the image bytes (unless you create a BASE64 string from them first), but use a VARBINARY
or IMAGE
column instead. 另外:不要使用
NVARCHAR
字段来存储图像字节(除非首先从它们创建BASE64字符串),而应使用VARBINARY
或IMAGE
列。
The problem is in the following line: 问题在以下行中:
str = string.Format("update Register set ... ,Logo='{5}' ...", ..., @"Logo", ...);
As you can see, you're formatting a string, but you don't insert the bytes from the image, but the word "Logo". 如您所见,您正在格式化字符串,但没有插入图像中的字节,而是插入了“ Logo”一词。
Assuming the column Logo
was of type IMAGE
or VARBINARY
, I would write something like this: 假设
Logo
列的类型为IMAGE
或VARBINARY
,我将这样写:
byte[] photo_array = null;
if (profPic.Image != null)
{
MemoryStream ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
photo_array = ms.GetBuffer();
}
if (photo_array != null)
{
SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=@logo", connection);
cmd.Parameters.AddWithValue("@logo", imageBytes);
cmd.ExecuteNonQuery();
}
Maybe I'm wrong but I'll try to do this 也许我错了,但我会尽力做到这一点
photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
}
con.Close();
This error may come when the lenght of the string is 0 当字符串的长度为0时,可能会出现此错误
Another thing is that you're not saving the image in the database 另一件事是您没有将图像保存在数据库中
//C# Code // C#代码
SqlCommand cmdSelect = new SqlCommand("select ImageValue from table where ID=1", ObjCon); SqlCommand cmdSelect =新的SqlCommand(“从ID = 1的表中选择ImageValue”,ObjCon); ObjCon.Open();
ObjCon.Open();
byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
ObjCon.Close();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
// 1.txt file will be created in c:\\temp folder // 1.txt文件将在c:\\ temp文件夹中创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.