本地图片插入到SQL Server中以及SQL Server中的导出图片

1. 建立数据库及数据库表

建表语句

CREATE table MyTable( 
id int identity(1,1) primary key , 
imageInfo IMAGE NULL 
) 

2. 建立C#项目及准备图片

3. 代码示例

  public void InsertImageToDataBase()
        {
            using (FileStream fs = File.OpenRead("pic.png"))
            {
                byte[] imageBytes = new byte[fs.Length];
                fs.Read(imageBytes, 0, Convert.ToInt32(fs.Length));
                string str = "insert into mytest(imageInfo) values(@imgfile)";
                SqlParameter parameter = new SqlParameter("@imgfile",imageBytes);
                int result = SqlHelper.ExecuteNonQuery(str, CommandType.Text, parameter);
                if (result > 0)
                {
                    MessageBox.Show("导入成功");
                }

            }
        }
  public void FromDataBaseToImage()
        {
          string sql = "select * from mytest";
         using (SqlDataReader reader = SqlHelper.ExecuteReader(sql,CommandType.Text))
         {
             if (reader.HasRows)
             {
                 while(reader.Read())
                 {
                     byte[] imageBytes = (byte[])reader[1];
                     int arraySize = imageBytes.GetUpperBound(0);
                     //将Excel写入文件、
                     using (FileStream fsWrite = File.OpenWrite("11.png"))
                     {
                         fsWrite.Write(imageBytes, 0, arraySize);
                     }

                 }
             }
         }
         MessageBox.Show("关闭");
        }

示例程序中用了SqlHelper类,如果不知道,请自行百度。
参考资料:网友SamZhang SQL Server中的Image数据类型的操作

你可能感兴趣的:(.NET)