C# 图片或PDF保存到SQL Server数据库

C# 图片或PDF保存到SQL Server数据库

数据库字段如下:图片保存要用image数据类型

C# 图片或PDF保存到SQL Server数据库_第1张图片

保存到数据库的两种方式:

 // 打开文件,获取图片路径
 OpenFileDialog openFileDialog = new OpenFileDialog();
 if (openFileDialog.ShowDialog() == DialogResult.Cancel)
 {
     return;
 }

 //pictureBox1.Image = Image.FromFile(openFileDialog.FileName);

 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
 //通过BinaryReader类对象的ReadBytes()方法将FileStream类对象转化为二进制数组
 BinaryReader br = new BinaryReader(fs);
 byte[] img = br.ReadBytes(Convert.ToInt32(fs.Length));
 
  // 方法一:通过参数的形式直接用Sql语句保存
 string insert = "insert into T_Img(ID,Img) values(@ID,@Img)";
 SqlParameter[] parameter = new SqlParameter[]
 {
     new SqlParameter("@ID", Convert.ToInt32(textBox1.Text)),
     new SqlParameter("@Img", img)
 };
 db.ExcuteBySqlParmeter(insert, parameter);

 // 方法二:使用SqlBulkCopy
 string sql = "select top 0 * from T_Img";
 DataSet ds = db.LoadDataSetBySql(sql);
 DataTable dtImg = ds.Tables[0];

 DataRow dr = dtImg.NewRow();
 dr["ID"] = Convert.ToInt32(textBox1.Text);
 dr["Img"] = img;
 dtImg.Rows.Add(dr);

 db.SaveImg(dtImg, "T_Img");

上面的ExcuteBySqlParmeter()和SaveImg()方法的详细代码如下:

public int ExcuteBySqlParmeter(string sql, SqlParameter[] sqlParmeter)
{
     int ir = 0;
     try
     {
      	 // GetConn():获取一个SqlConnection对象
         SqlCommand comm = new SqlCommand(sql, GetConn());
         comm.Parameters.AddRange(sqlParmeter);
         ir = comm.ExecuteNonQuery();
         CloseConn();
     }
     catch
     {
         ir = 0;
     }

     return ir;
}
 
public int SaveImg(DataTable dataTable, string TableName)
{
    int ir;
    try
    {
        SqlBulkCopy bulkCopy = new SqlBulkCopy(GetConn());  
        bulkCopy.DestinationTableName = TableName;//设置目标表的名称
        bulkCopy.WriteToServer(dataTable);  //保存
        ir = 1;
    }
    catch
    {
        ir = 0;
    }
    return ir;
}

从数据库读取图片并显示

private void GetImg()
{
    string sql = $"select top 1 * from T_Img where ID = {textBox1.Text}";
    DataSet ds = db.LoadDataSetBySql(sql);
    DataRow dr = ds.Tables[0].Rows[0];
    byte[] bytes = (byte[])dr["Img"];
    MemoryStream ms = new MemoryStream(bytes);
    this.pictureBox2.Image = Image.FromStream(ms);
}

你可能感兴趣的:(SQL,Server,数据库,c#,pdf)