300百分求向数据库插入图片和显示的问题
数据库为sql server,
表:student(code char(4),photo image)两个字段
求源代码
解决立刻给分

解决方案 »

  1.   

    我这个是ACCESS数据库你参考一下
    //save picture

    OleDbConnection mycnn=new OleDbConnection("provider=Microsoft.jet.oledb.4.0;data source=f:\\dazhu.mdb");
    mycnn.Open();

     OleDbCommand mycmd=new OleDbCommand("update info set picture=@a",mycnn );

    FileStream mystream=new FileStream("f:\\1.jpg",FileMode.Open,FileAccess.Read);
    long len=mystream.Length;

    mycmd.Parameters.Add("@a",OleDbType.Binary,(int)len,"picture");
    mycmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;
               
    byte []box=new byte[len]; 
    mystream.Read(box,0,(int)len);

    mycmd.Parameters["@a"].Value=box;

    //更新
    mycmd.ExecuteNonQuery();
    MessageBox.Show("ok");
    mystream.Close();
    mycnn.Close();
      

  2.   

    显示图片OleDbConnection mycnn=new OleDbConnection("provider=Microsoft.jet.oledb.4.0;data source=f:\\dazhu.mdb");
    mycnn.Open();
    MessageBox.Show("ok.mycnn.open");
    OleDbCommand mycmd=new OleDbCommand("select * from info",mycnn );
     OleDbDataReader myrd=mycmd.ExecuteReader();
    if(myrd.Read())
    {
    //读取图片
    byte []box=(byte [])myrd["picture"]; //构造流

    Stream stream1=new MemoryStream(box);
    this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);
                    
    stream1.Close();

    }


    mycnn.Close();
      

  3.   

    http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=26
    http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=6404
      

  4.   

    donet.aspx.cc孟子的网站,上面有你想要的文章,搜索sql即可。
      

  5.   

    我的是winform程序,要求用pictureBox控件来显示
      

  6.   

    保存图片到数据库后台代码
    namespace Drugger.WebUI.Modules
    {
      using System;
      using System.IO;
      using System.Text;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.Web.UI.HtmlControls;
      using Drugger.BusinessFacade;
      using Drugger.Model;
      using Drugger.SystemFramework;
      using Drugger.WebUI.Modules;
      using Drugger.WebCtrlLib;  /// <summary>
      /// 图片编辑控件
      /// </summary>
      public class PhotoEditModule: UserControl
      {
        protected RequiredFieldValidator valFilePhoto;
        protected RegularExpressionValidator valExpFilePhoto;
        protected HtmlInputFile filePhoto;    private void Page_Load(object sender, System.EventArgs e){}    #region 事件    // 保存相片数据
        protected void btnSave_Click(object sender, EventArgs e)
        {
          #region 获取数据      Stream imgStream = filePhoto.PostedFile.InputStream;
          int imgLength = filePhoto.PostedFile.ContentLength;
          byte[]imgData = new byte[imgLength];
          int n = imgStream.Read(imgData, 0, imgLength);      #endregion      if (Page.IsValid)
          {
            #region 保存数据到数据库        int retVal =  - 1;
            PhotoModel photoModel = new PhotoModel();
            PhotoSystem photoSystem = new PhotoSystem();
            PhotoModel.PhotoRow row = photoModel.Photo.NewPhotoRow();        row.Photo = imgData;        photoModel.Photo.Rows.Add(row);
            retVal = photoSystem.Insert(photoModel);        #endregion
          }
        }    #endregion    #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
          //
          // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
          //
          InitializeComponent();
          base.OnInit(e);
        }    /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器
        /// 修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
          this.Load += new System.EventHandler(this.Page_Load);    }
        #endregion
      }
    }前台代码
    <TABLE cellSpacing="1" cellPadding="3" width="100%" border="0">
    <TR>
    <TD>
    <INPUT id="filePhoto" type="file" name="filePhoto" runat="server">
    <asp:RequiredFieldValidator id="valFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="请选择图片"
    Display="Dynamic"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator id="valExpFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="图片格式错误"
    Display="Dynamic" ValidationExpression="[a-zA-Z]:\\(.+\\)*.+(\.gif|\.jpeg|\.jpg)"></asp:RegularExpressionValidator>
    <P>注:上传的图片必须为gif或jpeg格式,图片规格默认为94×114(最佳浏览效果)</P>
    </TD>
    </TR>
    </TABLE>
    <TABLE WIDTH="100%" BORDER="0" CELLSPACING="1" CELLPADDING="3">
    <TR>
    <TD width="40">&nbsp;</TD>
    <TD height="40">
    <asp:Button id="btnSave" runat="server" Text="保存" Width="60" OnClick="btnSave_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:HyperLink id="hlkReturn" runat="server" Text="返回" Absoluted="True" CssClass="Button" Width="60" />
    </TD>
    </TR>
    </TABLE>显示图片前台代码
    <%@ Page language="c#" Codebehind="Picture.aspx.cs" AutoEventWireup="false" Inherits="Drugger.WebUI.Modules.Picture" EnableSessionState="False" enableViewState="False" %>后台代码
    namespace Drugger.WebUI.Modules
    {
      using System;
      using System.Text;
      using System.IO;
      using System.Web.UI;
      using System.Web.UI.HtmlControls;
      using Drugger.BusinessFacade;
      using Drugger.SystemFramework;  /// <summary>
      /// 图片显示Web页
      /// </summary>
      public class Picture: Page
      {
        private void Page_Load(object sender, EventArgs e)
        {
          if (!Page.IsPostBack)
          {
            int photoId = 0;
            string photoIdText = Request.QueryString.Get("photoId");
            photoId = (int)photoIdText;
            byte[]photo = (new PhotoSystem()).GetPhotoByPhotoID(photoId);        if (photo != null)
            {
              Response.ContentType = "image/*";
              Response.BinaryWrite(photo);
            }
          }
        }    #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
          //
          // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
          //
          InitializeComponent();
          base.OnInit(e);
        }    /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
          this.Load += new EventHandler(this.Page_Load);
        }
        #endregion
      }
    }数据库提取代码:
    /// <summary>
    /// 获取图片
    /// </summary>
    /// <param name="photoId">图片ID</param>
    /// <returns>图片</returns>
    public byte[]GetPhotoByPhotoID(int photoId)
    {
      byte[]photo = null;
      string spString = "GetPhotoByPhotoID";  SqlParameter[]parms = SqlHelperParameterCache.GetSpParameterSet
        (AccessCommon.ConnectionString, spString);
      parms[0].Value = photoId;  using(SqlDataReader rdr = SqlHelper.ExecuteReader
        (AccessCommon.ConnectionString, CommandType.StoredProcedure, spString,
        parms))
      {
        if (rdr.Read())
        {
          if (!rdr.IsDBNull(0))
            photo = (byte[])rdr[0];
        }
      }  return photo;
    }
      

  7.   

    我是用Winfrom开发,希望能帮到你
    先建一个类,Copy可用..........
    using System;
    using System.IO;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Runtime.Serialization.Formatters.Binary; //引入供序列化Image对象使用namespace Common
    {
    /// <summary>
    /// 实现Image与byte[]之间的转换
    /// </summary>
    public class ReadWriteImage
    {
    private ReadWriteImage(){}
    /// <summary>
    /// 将byte[]转换为Image
    /// </summary>
    /// <param name="bytes">字节数组</param>
    /// <returns>Image</returns>
    public static Image ReadImage(byte[] bytes)
    {
    MemoryStream ms=new MemoryStream(bytes,0,bytes.Length);
    BinaryFormatter bf = new BinaryFormatter();
    object obj=bf.Deserialize(ms);
       ms.Close();
       return (Image)obj;
    }
    /// <summary>
    /// 将Image转换为byte[]
    /// </summary>
    /// <param name="image">Image</param>
    /// <returns>byte[]</returns>
    public static byte[] ConvertImage(Image image)
    {
    MemoryStream ms=new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms,(object)image); 
    ms.Close();
    return ms.ToArray();
    }
    }
    }
      

  8.   


    FileStream stream=new FileStream("c:\\w.jpg",FileMode.Open,FileAccess.Read);
    byte[] blob=new byte[stream.Length];
    stream.Read(blob,0,(int)stream.Length);
             stream.Close();
             string source="server=csl;database=StudentDB;uid=sa;pwd=''";
    sqlcon=new SqlConnection(source);
    try
             {
       sqlcon.Open();
       string sql="insert into photo(code,photo) values('0001',@photo)";
       SqlCommand command=new SqlCommand(sql,sqlcon);
       cmd.Parameters.Add("@photo",blob);
       //cmd.Parameters.Add("@photo", SqlDbType.Image, blob.Length).Value = blob;
                cmd.ExecuteNonQuery();
              }
       catch(Exception e1)
     {
       Console.WriteLine("shiba");
     }
     finally
     {
       sqlcon.Close();
     }
    }在插入数据库时,不包任何错误,但数据库中没有数据我的数据库是sqlserver 表结构为photo(code char(4),photo image)
      

  9.   

    SQL数据库
     mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
    mycnn.Open();
     SqlCommand mycmd=new SqlCommand("update picture set picture=@a where ID=1",mycnn);

    FileStream mystream=new FileStream("f:\\1.jpg",FileMode.Open,FileAccess.Read);
    long len=mystream.Length;

    mycmd.Parameters.Add("@a",SqlDbType.Image,(int)len,"picture");
    mycmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;
               
    byte []box=new byte[len]; 
    mystream.Read(box,0,(int)len); mycmd.Parameters["@a"].Value=box;

    //更新
    mycmd.ExecuteNonQuery();
    MessageBox.Show("ok");
    mystream.Close();
    mycnn.Close();
      

  10.   

    显示到PICTURE控件
    mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
    mycnn.Open();
    MessageBox.Show("ok.mycnn.open");
    SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
    SqlDataReader  myrd=mycmd.ExecuteReader();  


    if(myrd.Read())
    {
    //读取图片
    if(!myrd.IsDBNull(1))
    {
    byte []box=(byte [])myrd[1];

    //构造流

    Stream stream1=new MemoryStream(box);
    this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);

    stream1.Close();
    }
    else
    {                MessageBox.Show("该字段是NULL");
    }

    }


    mycnn.Close();
    }
    catch(Exception my)
    {
                 MessageBox.Show(my.Message.ToString()); }
      

  11.   

    把我刚才发的两个方法Copy过到同一文件去.然后把这句话改了,试一下cmd.Parameters.Add(new SqlParameter("@photo",SqlDbType.Image));
    cmd.Parameters["@photo"].Value = ConvertImage(System.Drawing.Image.FromFile("c:\\w.jpg"));
      

  12.   

    mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
    mycnn.Open();
    MessageBox.Show("ok.mycnn.open");
    SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
    SqlDataReader  myrd=mycmd.ExecuteReader();  


    if(myrd.Read())
    {
    //读取图片
    if(!myrd.IsDBNull(1))
    {
    byte []box=(byte [])myrd[1];

    //构造流

    Stream stream1=new MemoryStream(box);
    this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);

    stream1.Close();
    }
    else
    {                MessageBox.Show("该字段是NULL");
    }

    }


    mycnn.Close();
    }
    catch(Exception my)
    {
                 MessageBox.Show(my.Message.ToString()); }
      

  13.   

    源码参考:
           http://www.pcsky.cn/article/list.asp?id=774看不懂再问
      

  14.   

    添加:
      http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506
    显示:
      http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1
      

  15.   

    插入数据库就是先把图片转换成byte[],然后用Command对象写入数据库,取出也是如此,
      

  16.   

    呵呵.托孟老大的福呢...
    http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1