2017-07-16 26 views
0

我想下面的代码在C#windows应用程序工作正常,从SQL Server数据库表中检索单个图像。如何从C#windows应用程序的picturebox中的SQL Server数据库检索多个图像?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 
using System.Data.SqlClient; 

namespace ManagementSystem 
{ 
    public partial class frmSearchResult : Form 
    { 
     public frmSearchResult() 
     { 
      InitializeComponent(); 
     } 

     SqlConnection con; 
     SqlCommand cmd; 

     private void cmdSearch_Click(object sender, EventArgs e) 
     { 
      con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=managementsystem;Integrated Security=True"); 
      con.Open(); 

      cmd = new SqlCommand("Select M_Photo, S_Photo From Members where M_Number=15", con); 

      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      DataSet ds = new DataSet(); 

      da.Fill(ds); 

      if (ds.Tables[0].Rows.Count > 0) 
      { 
       MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["M_Photo"]); 
       pic_M.Image = new Bitmap(ms); 
      } 
     } 
    } 
} 

但我需要从数据库检索多个图像。当我追加下面的代码在最后,我得到一个错误:

Parameter is not valid.

附加码是

MemoryStream ms1 = new MemoryStream((byte[])ds.Tables[0].Rows[0]["S_Photo"]); 
pic_S.Image = new Bitmap(ms1); 

有什么不对呢?请帮忙。

谢谢!

+2

noooo ...从不保存SQL中的图像! – Proxytype

+0

请告诉我,保存和检索图像的最佳方式是什么@Proxytype –

+0

对图像使用某种类型的blob或文件存储,并保留对数据库中图像的引用。将表中的图像保存在数据库中。 –

回答

0

主要问题是以正确的方式保存图像。使用下面的代码为每个图像保存数据库图像字段中的图像,并使用上面提问代码来检索图像。

//Convert image to binary 
string imgpathC2 = txtH_C2.Text; 
FileStream fsC2; 
fsC2 = new FileStream(@imgpathC2, FileMode.Open, FileAccess.Read); 
byte[] picbyteC2 = new byte[fsC2.Length]; 
fsC2.Read(picbyteC2, 0, System.Convert.ToInt32(fsC2.Length)); 
fsC2.Close(); 

//Add binary value to SQL parameter 
SqlParameter picparaC2 = new SqlParameter(); 
picparaC2.SqlDbType = SqlDbType.Image; 
picparaC2.ParameterName = "picC2"; 
picparaC2.Value = picbyteC2; 

//use parameter in command 
cmd.Parameters.Add(picparaC2); 

谢谢!

相关问题