//将SQL server2000中保存的图像显示在Picture中 
byte[] buffByte = null; 
string comm = @"select img from table1 where id = " + this.listBox1.SelectedValue ; 
this.sqlCommand1 = new System.Data.SqlClient.SqlCommand (); 
this.sqlCommand1.CommandType = System.Data.CommandType.Text ; 
this.sqlCommand1.CommandText = comm; 
this.sqlCommand1.Connection = this.sqlConnection1 ; 
this.sqlConnection1.Open(); 
System.Data.SqlClient.SqlDataReader rd = this.sqlCommand1.ExecuteReader(); 
while (rd.Read()) 

buffByte = ((byte[])rd[0]); 

rd.Close(); 
this.sqlConnection1.Close(); 
//将图像的字节数组放入内存流 
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffByte); 
//通过流对象建立Bitmap 
System.Drawing.Bitmap bmp = new Bitmap(ms); 
this.pictureBox1.Image = bmp; 
//将图像读入到字节数组 
System.IO.FileStream fs = new System.IO.FileStream(pathName,System.IO.FileMode.Open,System.IO.FileAccess.Read); 
byte[] buffByte = new byte[fs.Length]; 
fs.Read(buffByte,0,(int)fs.Length); 
fs.Close(); 
fs = null; //将图像保存到SQL server2000中
//建立Command命令 
string comm = @"Insert into table1(img,name) values(@img,@name)"; 
this.sqlCommand1 = new System.Data.SqlClient.SqlCommand (); 
this.sqlCommand1.CommandType = System.Data.CommandType.Text ; 
this.sqlCommand1.CommandText = comm; 
this.sqlCommand1.Connection = this.sqlConnection1 ; 
//创建Parameter 
this.sqlCommand1.Parameters.Add("@img",System.Data.SqlDbType.Image); 
this.sqlCommand1.Parameters[0].Value = buffByte; 
this.sqlCommand1.Parameters.Add("@name",System.Data.SqlDbType.VarChar); 
this.sqlCommand1.Parameters[1].Value =pathName.Substring(pathName.LastIndexOf("\\")+1); 
try 

this.sqlConnection1.Open(); 
this.sqlCommand1.ExecuteNonQuery(); 
this.sqlConnection1.Close(); 

catch(System.Exception ee) 

MessageBox.Show(ee.Message ); 

buffByte = null; 

解决方案 »

  1.   

    Byte[] FileByteArray = new Byte[FileLength];   //图象文件临时储存Byte数组
    Stream StreamObject = UpFile.InputStream;      //建立数据流对像
    //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
    StreamObject.Read(FileByteArray,0,FileLength);  
    //建立SQL Server链接
    SqlConnection Con = new SqlConnection("Data Source=Localhost;InitialCatalog=testdb;User ID=sa;Pwd=;");
    String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType,ImageDescription, ImageSize) valueS (@Image, @ContentType,@ImageDescription, @ImageSize)";
    SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
    CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).value =FileByteArray;
    CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).value =UpFile.ContentType;  //记录文件类型
    //把其它单表数据记录上传
    CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).value =txtDescription.Text;
    //记录文件长度,读取时使用
    CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).value =UpFile.ContentLength;
    Con.Open();
    CmdObj.ExecuteNonQuery();
    Con.Close();