博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#操作varbinary(MAX)字段
阅读量:5226 次
发布时间:2019-06-14

本文共 2992 字,大约阅读时间需要 9 分钟。

如果把照片直接保存在SQL Server数据库中,微软推荐用varbinary(MAX)字段。下面的代码演示了用C#操作varbinary(MAX)字段的基本方法。

1、新增记录

        private void btnBrowse_Click(object sender, EventArgs e)//浏览照片

        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "*.jpg(jpg文件)|*.jpg|*.gif|*.gif";
            dlg.FilterIndex = 1;
            if (dlg.ShowDialog()==DialogResult.OK)
            {
                textBox3.Text = dlg.FileName;
                pictureBox1.Image = Image.FromFile(dlg.FileName);
            }
        }

    //新增记录

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))

            {
                String sql = "insert into emp(name,age,photo) values(@name,@age,@photo)";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@name", textBox1.Text);
                cmd.Parameters.AddWithValue("@age", Convert.ToInt32(textBox2.Text));
                //byte[] b;
                //using(FileStream fs=new FileStream(textBox3.Text,FileMode.Open,FileAccess.Read))
                //{
                //    b = new byte[fs.Length];
                //    fs.Read(b, 0, (int)fs.Length);
                //}
                byte[] b;
                if (textBox3.Text != "")
                {
                    b = File.ReadAllBytes(textBox3.Text);
                    cmd.Parameters.AddWithValue("@photo", b);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@photo", System.Data.SqlTypes.SqlBinary.Null);
                }
                conn.Open();
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);

                }

            }

2、显示记录信息并提供修改功能

        private void FormDetail_Load(object sender, EventArgs e)//显示记录详细信息

        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
            {
                String sql = "select * from emp where id=@id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@id", id);
                conn.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if(dr.Read())
                    {
                        textBox1.Text = dr[1].ToString();
                        textBox2.Text = dr[2].ToString();
                        if (!dr.IsDBNull(3))//防止照片字段为空
                        {
                            System.Data.SqlTypes.SqlBytes bytes = dr.GetSqlBytes(3);
                            pictureBox1.Image=Image.FromStream(bytes.Stream);//显示照片
                        }
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)//更新记录

        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
            {
                byte[] b;
                if (textBox3.Text != "")//需要更新照片
                {
                    String sql = "update emp set name=@name,age=@age,photo=@photo where id=@id";
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@name", textBox1.Text);
                    cmd.Parameters.AddWithValue("@age", Convert.ToInt32(textBox2.Text));
                    cmd.Parameters.AddWithValue("@id", id);
                    b = File.ReadAllBytes(textBox3.Text);
                    cmd.Parameters.AddWithValue("@photo", b);
                    conn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.Message);

                    }
                }
                else//不需要更新照片
                {
                    String sql = "update emp set name=@name,age=@age where id=@id";
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@name", textBox1.Text);
                    cmd.Parameters.AddWithValue("@age", Convert.ToInt32(textBox2.Text));
                    cmd.Parameters.AddWithValue("@id", id);
                    conn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.Message);

                    }
                }              
            }
        }

转载于:https://www.cnblogs.com/zhouhb/archive/2013/02/13/2910808.html

你可能感兴趣的文章
尼玛某前辈把ant 工程 改成android studio工程然后上传了 对我来说 尼玛这玩意就和屎一样...
查看>>
SSM整合(精简版)
查看>>
各种xml文件约束,Eclipse用
查看>>
泰勒展开,傅里叶变换,拉普拉斯变换和Z变换的物理意义
查看>>
Java Concurrentmodificationexception异常原因和解决方法
查看>>
Python 面向对象(其四)
查看>>
客户端访问浏览器的流程
查看>>
Linux——ls
查看>>
操作系统(八) 死锁
查看>>
codeforces水题100道 第二十二题 Codeforces Beta Round #89 (Div. 2) A. String Task (strings)
查看>>
c++||template
查看>>
shell编程 遍历目录文件
查看>>
Python接口自动化测试_悠悠
查看>>
(转)python学习笔记5--decimal
查看>>
[BZOJ 5323][Jxoi2018]游戏
查看>>
编程面试的10大算法概念汇总
查看>>
Load generator连接失败的解决办法!(转)
查看>>
STM32 HAL库学习系列第7篇---定时器TIM 输入捕获功能
查看>>
PHP中file_get_contents函数获取带BOM的utf-8,然后json_decode() 返回null的问题
查看>>
SQLServer代理新建或者编辑作业报错
查看>>