(转帖)C#存取SQL Server数据库之一:二进制存取图片文件

创建项目

1.      添加一个名为RWTest的表到 SQL Server MYTest 数据库。 表字段设置如下:

 a.      唯一标识字段名称为"ID",类型为Int

 b.       名称为"Description"VarChar类型的字段,字段长度为50

 c.      名称为"ImgField" Image 类型的字段。

2.      启动 Visual Studio .NET 并创建一个新的 Visual C# Windows 应用程序项目。

3.      从工具栏中拖两个Button 控件到默认窗体, Form1

4.      在属性窗口中修改NamebuttonFileToDB Text 属性为从文件保存到数据库 然后修改NamebuttonDBToFile Text 属性为从数据库保存到文件

5 从工具栏放置2TextBox1PictureBox控件:Name属性分别为:textBoxGetID,           textBoxGetDescription, pictureBoxGetImage, 显示从数据库读出的IDDescriptionImgField字段。

 

源码实例

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;

using System.Collections;

//数据库说明:MyTest数据库,RWTest,包含3列:ID(int),Description(varchar(50),ImgField(Image)

 

namespace RWImgSQL

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void buttonFileToDB_Click(object sender, EventArgs e)

        {

            SqlConnection sqlConnection = new SqlConnection("Data Source = liuxueqin; Initial Catalog=MyTest;Integrated Security=True");

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("Select * from RWTest", sqlConnection);

            SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            DataSet dataSet = new DataSet("RWTest");

            sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;//确定现有 DataSet 架构与传入数据不匹配时需要执行的操作。

 

            String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

            string ImageFile = System.IO.Path.GetDirectoryName(CurrentExeName) + "//F1.jpg";

            System.IO.FileStream fileStream = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            byte[] myData = new byte[fileStream.Length];

            fileStream.Read(myData, 0, System.Convert.ToInt32(fileStream.Length));//从流中读取字节块,并将数据写入到该缓冲区

            fileStream.Close();

            try

            {

                sqlDataAdapter.Fill(dataSet, "RWTest");

                //DataRow表示DataTable中的一行数据

                System.Data.DataRow dataRow;

                dataRow = dataSet.Tables["RWTest"].NewRow();

                dataRow1["ID"] = 1;

                dataRow1["Description"] = "This would be description text";

                dataRow1["ImgField"] = myData;

 

                dataSet.Tables["RWTest"].Rows.Add(dataRow);

                sqlDataAdapter.Update(dataSet, "RWTest");

                sqlConnection.Close();

                MessageBox.Show("写入数据库成功!", " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            catch (Exception ex)

            {

                if (sqlConnection.State == ConnectionState.Open)

                {

                    sqlConnection.Close();

                }

                MessageBox.Show("写入数据库失败"+ex.Message, " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        private void buttonDBToFile_Click(object sender, EventArgs e)

        {

            SqlConnection sqlConnection = new SqlConnection("Data Source=liuxueqin;Initial Catalog=MyTest;Integrated Security=True");

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("Select * from RWTest", sqlConnection);

            SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            DataSet dataSet = new DataSet("RWTest");

 

            byte[] MyData = new byte[0];

            sqlDataAdapter.Fill(dataSet, "RWTest");

            DataRow myRow;

            myRow = dataSet.Tables["RWTest"].Rows[0];

            MyData = (byte[])myRow["imgField"];

 

            int ArraySize = MyData.GetUpperBound(0);

            String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

            string ImageFile = System.IO.Path.GetDirectoryName(CurrentExeName) + "//F2.jpg";

            FileStream fs = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.Write);

            fs.Write(MyData, 0, ArraySize);

            fs.Close();

 

            //---在界面上的2textBox1pictureBox,用来显示从数据库中读出的IDDescriptionImageField字段

            textBoxGetID.Text = myRow["ID"].ToString();

            textBoxGetDescription.Text = myRow["Description"].ToString();

            pictureBoxGetImage.Image = Image.FromFile(ImageFile);

 

            if (sqlConnection.State == ConnectionState.Open)

            {

                sqlConnection.Close();

            }

            MessageBox.Show(" 从数据库读出数据成功!", " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值