嘿伙计们,在Windows应用程序的c sharp 2008中,任何人都可以帮助我在sql数据库的文件夹和路径中添加图像吗?
答案 0 :(得分:1)
以下是您可以尝试的一些代码,
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo imageInfo = new FileInfo(File1.Value.Trim());
if (!imageInfo.Exists)
//Show msg for "please select one image file."
else
{
switch (imageInfo.Extension.ToUpper())
{
case ".JPG": this.UpLoadImageFile(imageInfo); break;
case ".GIF": this.UpLoadImageFile(imageInfo); break;
case ".BMP": this.UpLoadImageFile(imageInfo); break;
default: //Show msg "file type error."; break;
}
}
}
private void UpLoadImageFile(FileInfo info)
{
SqlConnection objConn = null;
SqlCommand objCom = null;
try
{
byte[] content = new byte[info.Length];
FileStream imagestream = info.OpenRead();
imagestream.Read(content, 0, content.Length);
imagestream.Close();
objConn = new SqlConnection(strConnectionString);
objCom = new SqlCommand("insert into TableName(FieldName,Picture)values(@FieldName,@Picture)", objConn);
SqlParameter FieldNameParameter = new SqlParameter("@FieldName", SqlDbType.NVarChar);
if (this.txtFileName.Text.Trim().Equals(""))
FieldNameParameter.Value = "Default";
else
FieldNameParameter.Value = this.txtFileName.Text.Trim();
objCom.Parameters.Add(FieldNameParameter);
SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image);
pictureParameter.Value = content;
objCom.Parameters.Add(pictureParameter);
objConn.Open();
objCom.ExecuteNonQuery();
objConn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
objConn.Close();
}
}
答案 1 :(得分:0)
如果您有路径
,则为示例代码byte[] img = File.ReadAllBytes("your image path");
mySqlCommand = "INSERT INTO MyTable(Image) VALUES(@Image)";//mySqlCommand is a SqlCommand, and @Image is a parameter
mySqlCommand.Parameters.AddWithValue("@Image", img);
mySqlCommand.ExecuteNonQuery();
答案 2 :(得分:0)
如果您正在使用Windows表单,那么很好的将图片保存为数据库中的图像文件。以下代码可以帮助您:
OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = JPG|*.jpg|GIF|*.gif|PNG|*.png|BMP|*.bmp";
if (DialogResult.OK == ofDlg.ShowDialog())
{
textBox1.Text = ofDlg.FileName;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
picturebox.Image = new Bitmap(ofDlg.OpenFile());
}
//在databasew中保存时
db.conopen(); byte [] img = File.ReadAllBytes(image);
string query = "update tbl_emp_info set EMP_PHOTO=@image where EMP_ID=@empid";
cmd=new SqlCommand(query,db.con);
cmd.Parameters.AddWithValue("@Image",img);
cmd.Parameters.AddWithValue("empid", Emp_id);
cmd.ExecuteNonQuery();