C# 保存图像文件到SQL SERVER数据库,再读取该文件并显示

 需要在SQL SERVER中创建数据库test, 然后再test中创建一个数据表ImageTable,
含字段 id  int  自动增长
ImagePath  nchar(50)
Image    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.SqlClient;
using System.IO;

namespace SaveImageToSqlServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonSaveImageToDataServer_Click(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.ShowDialog();

            string dirName = this.folderBrowserDialog1.SelectedPath;
            DirectoryInfo dir = new DirectoryInfo(dirName);
            FileInfo[] fileInfos = dir.GetFiles("*.jpg");                     //获取文件夹下所有jpg文件,因为图像文件都很大的,选取文件夹下不要有太多图片,否则Primary区会满了,系统会提示无法再插入数据。
            List<string> fileList = new List<string>(100);   
            foreach (FileInfo fileInfo in fileInfos)
            {
                fileList.Add(fileInfo.FullName);
                System.Windows.Forms.Application.DoEvents();
            }

            #region Save data to Data Server
            string strConn =                              // 设置连接字符串,我是在本机上连接,远程的话需要修改连接字符串
                @"Server=(local);"
            + @"Initial Catalog=test;"
            + @"User Id =fisherman;"
            + @"Password=;"
            + @"Integrated Security = true";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(strConn))    // 使用using 可以及时释放资源
                {
                    sqlConnection.Open();
                    foreach (string file in fileList)
                    {
                        // 图像文件存放在数据库中,需要先转换成二进制流。使用byte【】来保存。
                        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                        byte[] byteImage = new byte[fileStream.Length];
                        fileStream.Read(byteImage, 0, (int)fileStream.Length);
                        
                       //平时写代码,对于Insert语句,喜欢直接用“Insert into tableName(a,b)Values(a1,b1)” 是完成,但是对于二进制流,这样写
                        // 会报错,必须按照下面的方式,设置参数名称类型。
                        string commandText = "Insert into ImageTable(ImagePath, Image)Values(@ImagePath, @Image)";
                        SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
                        sqlCommand.Parameters.Add("@ImagePath", SqlDbType.Text);      // 图像文件路径
                        sqlCommand.Parameters.Add("@Image", SqlDbType.Binary);         // 图像文件数据,使用二进制格式。
                        sqlCommand.Parameters["@ImagePath"].Value = file;
                        sqlCommand.Parameters["@Image"].Value = byteImage;              // 将图像赋值给command

                        sqlCommand.ExecuteNonQuery();                   

                        System.Windows.Forms.Application.DoEvents();
                    }
                  sqlConnection.Close();       // 用完之后,必须显示关闭
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            #endregion
            MessageBox.Show("Save data OK.");
        }

        private void buttonShowImage_Click(object sender, EventArgs e)
        {
            // 连接字符串,同上
            string strConn =
                @"Server=(local);"
            + @"Initial Catalog=test;"
            + @"User id=fisherman;"
            + @"Password=;"
            + @"Integrated Security=true;";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(strConn))
                {
                    sqlConnection.Open();
                    string commandText = "Select ImagePath, Image from ImageTable";     // 查询ImageTable中的数据
                    SqlDataAdapter adapter = new SqlDataAdapter(commandText, sqlConnection);   // 使用DataTable来保存数据,以便赋值给DataGridView, 函数结束后,窗体上的DataGridView会显示,2列,一列是Image。
                    // Row和Column间距太小,不太好看,不过至少图片能够显示。
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    this.dataGridView1.DataSource = dt;
                    sqlConnection.Close();
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值