读写数据库图象字段

来源:互联网 发布:如何设置网络共享盘 编辑:程序博客网 时间:2024/05/16 15:14

从论坛上看到好多人在讨论这方面的问题,把代码整理出来,说不定回答问题的时候还能用上呢。

首先,是数据库的设计。我使用的Access数据库。定义一个数据表photo.mdb,定义两个字段photoID和photo ,其中photoID为主键,字段类型为“文本”,photoID的字段类型为“OLE对象”。(注意:如果采用SQL数据库photo的字段类型为“image “。

以字节形式读写数据库图象字段:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;

namespace WindowsApplication2
{
    
public partial class Form1 : Form
    
{
        
public OleDbConnection dbconn = new OleDbConnection();
        
public OleDbCommand comm = new OleDbCommand();
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void Form1_Load(object sender, EventArgs e)
        
{
            
this.OpenConn();
            
this.pictureBox1.Image = null;
            Image im;
            
this.getPhoto("0000"out im);
            
this.pictureBox1.Image = im;
           
        }

        
/// <summary>
        
/// 从数据库中读取图象
        
/// </summary>
        
/// <param name="pid"></param>
        
/// <param name="im"></param>

        public void getPhoto(string pid, out Image im)
        
{
            
//读取图象 
            im = null;
            OleDbDataReader dr 
= SelectDR("select top 1 photo from photo where photoid='" + pid + "'");
            
if (dr.HasRows)
            
{
                dr.Read();
                
if (dr[0!= DBNull.Value)
                
{
                    
try
                    
{
                        Byte[] byteBLOBData 
= new Byte[0];

                        byteBLOBData 
= (Byte[])dr[0];
                        MemoryStream stmBLOBData 
= new MemoryStream(byteBLOBData);
                        im 
= Image.FromStream(stmBLOBData);
                    }

                    
catch (Exception ex)
                    
{
                        MessageBox.Show(ex.Message);
                    }

                }

                
else
                
{
                    im 
= null;
                }

            }

            dr.Close();

        }

        
/// <summary>
        
/// 查询
        
/// </summary>
        
/// <param name="SqlStr"></param>
        
/// <returns></returns>

        public OleDbDataReader SelectDR(string SqlStr)
        
{
            OleDbCommand cmd 
= new OleDbCommand(SqlStr, dbconn );
            
return cmd.ExecuteReader();
        }

        
/// <summary>
        
/// 打开数据库连接。
        
/// </summary>

        public void OpenConn()
        
{
            
if (dbconn.State.ToString() == "Closed")
            
{
                
//DBConn.ConnectionString=ConfigurationSettings.AppSettings["constring"];    //."user id=sa;data source=127.0.0.1;persist security info=True;initial catalog=PPF;password=7388";
                dbconn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=" + Application.StartupPath + @"dataphoto.mdb;User ID=Admin;Password=";
                
try
                
{
                    dbconn.Open();
                }

                
catch
                
{
                    MessageBox.Show(
"数据库连接失败");
                }


            }

        }

        
private void button1_Click(object sender, EventArgs e)
        
{
            savePhoto(
"0000"this.pictureBox1.Image);
        }

        
/// <summary>
        
/// 保存图象到数据库
        
/// </summary>
        
/// <param name="pid"></param>
        
/// <param name="im"></param>

        public void savePhoto(string pid, Image im)
        
{
            OleDbCommand cmd;
            OleDbDataReader dr 
= SelectDR("select photoid from  photo where photoID='" + pid + "'");

            
if (dr.HasRows) //is exist
            {
                cmd 
= new OleDbCommand("Update photo set photoID=@pid, photo=@photo where photoID='" + pid + "'", dbconn );
            }

            
else  // not exist
            {
                cmd 
= new OleDbCommand("Insert Into photo (photoID,photo) Values(@pid,@photo) ", dbconn );
            }

            dr.Close();
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue (
"@pid", pid);
            cmd.Parameters.AddWithValue (
"@photo", DBNull.Value);

            
//将图片保存到数据库中 
            if (im == null)
            
{
                cmd.Parameters[
"@photo"].Value = DBNull.Value;
            }

            
else
            
{
                
try
                
{
                    MemoryStream ms 
= new MemoryStream();
                    im.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    
byte[] myData = new Byte[ms.Length];
                    ms.Position 
= 0;
                    ms.Read(myData, 
0, Convert.ToInt32(ms.Length));
                    cmd.Parameters[
"@photo"].Value = myData;

                }

                
catch (System.Exception ee)
                
{
                    MessageBox.Show(ee.Message);
                }

            }
//else 

            cmd.ExecuteNonQuery();
        }

    }

}
原创粉丝点击