【问题标题】:How to save 1 file PDF to SQL Server with WinForm如何使用 WinForm 将 1 个文件 PDF 保存到 SQL Server
【发布时间】:2026-02-22 11:20:03
【问题描述】:

代码查询数据库

我无法将 PDF 文件保存到我的数据库中,我的数据库存储区域出现了严重问题。

public void ADDWORK(String MAW, string NAMEW, string IDUSER, bool Image,string room, byte[] document,string content,bool donework)
{
    String strSql = string.Format("INSERT INTO WORK(IDWORD,NAMEWORk,IDUSER,IMAGES,IDROOM,DOCUMENTS,CONTENT,DONEWORK)VALUES('{0}',N'{1}',N'{2}','{3}',N'{4}',N'{5}',N'{6}',N'{7}')"
        , MAW, NAMEW, IDUSER, Image,room,document,content,donework);
    db.ExecuteNonQuery(strSql);
}

代码调用函数:

byte[] pdf;
public void UploadFlie(string file)
{
    FileStream fileStream = File.OpenRead(file);
    byte[] contents = new byte[fileStream.Length];
    fileStream.Read(contents, 0, (int)fileStream.Length);
    fileStream.Close();
    pdf = contents;
}

private void button1_Click(object sender, EventArgs e)
{
    UploadFlie(filename);
     dg.ADDWORK(idword, textBox1.Text,"1",  false,"ROOM1", pdf, richTextBox1.Text, false);
    MessageBox.Show("Done!");
}

【问题讨论】:

  • 我不得不指出您有一个 SQL 注入漏洞。您正在将任意字符串格式化为 SQL 字符串表达式、'{0}' 等。使用参数。请。
  • 为什么要用文件填充非常昂贵的 SQL Server 存储空间(和内存)?这就是文件系统高效(且具有成本效益)所做的事情。使用数据库的资源来填充 PDF 文件似乎......反利润。
  • 关于参数化查询的进一步说明...您有一个byte[] document 参数,它将被格式化为'System.Byte[]',这不是一个有效的varbinary 表达式,而且绝对是无论如何,这不是您想要的。参数将保护您免受此类错误的影响。
  • 以下内容可能会有所帮助:*.com/questions/66612039/…。如果使用SqlDbType.VarBinary,请将大小设置为-1。您可以考虑将文件名存储在数据库中,并将实际文件保存在文件系统中。
  • db.ExecuteNonQuery(strSql); 建议您在方法之间共享单个 SqlCommand 对象。不要那样做,您应该在需要时创建 SqlConnectionSqlCommand 对象,并在使用完毕后立即处理它们。 (using 构造将负责自动处理。)这也将使您更容易使用带有SqlParameter 的参数化查询,而不是像您当前尝试那样尝试将值注入查询。

标签: c# sql-server winforms pdf


【解决方案1】:

这是我的示例,如何获取任何文件并将其保存在数据库中。

我使用两种不同的方法

  1. 保存字节数组。
  2. 保存流

首先你需要创建列 varbinary(MAX) 在我的例子中我称之为 - PdfFilePdfExtn 列将文件的类型保存为 varchar(10)(可以使用 4)。

  1. 保存字节数组:

         private void btnGetFile_Click(object sender, EventArgs e)
     {
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
         if (result == DialogResult.OK) // Test result.
         {
             string file = openFileDialog1.FileName;
             string extn = new FileInfo(file).Extension;
    
             try
             {
                 byte[] fileBytes = File.ReadAllBytes(file);
                 string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (@Id,@FirstName,@LastName,@Email,@Password,@PdfFile,@FileExtn)";
    
                 List<SqlParameter> l = new List<SqlParameter>();
                 l.Add(new SqlParameter("@Id", "101"));
                 l.Add(new SqlParameter("@FirstName", "Aviv"));
                 l.Add(new SqlParameter("@LastName", "Halevy"));
                 l.Add(new SqlParameter("@Email", "Assadsa@gmail.com"));
                 l.Add(new SqlParameter("@Password", "123456"));
                 SqlParameter sp = new SqlParameter("@PdfFile", SqlDbType.VarBinary, -1);
                 sp.Value = fileBytes;
                 l.Add(sp);
                 l.Add(new SqlParameter("@FileExtn", extn));
                 if (DAL.Database.ParametersCommand(cmd, l) > 0)
                     textBox1.Text = "SUCCESS! Save with byte array";
             }
             catch (IOException ex)
             {
    
             }
         }
     }
    

从字节写入文件:

  private void btnReadFromDb_Click(object sender, EventArgs e)
    {
        string cmd = "SELECT * FROM Employee WHERE Id = '101'";
        string path = "YOUR_PATH\\Test";
        DataTable dt = DAL.Database.GetDataTable(cmd);
        if (dt != null && dt.Rows.Count > 0)
        {
            Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
            string extn = dt.Rows[0]["FileExtn"].ToString();
            path = Path.Combine(path, "Test321"+extn);

            File.WriteAllBytes(path, file);
            Process.Start(path);
        }
    }

结果:

  1. 使用流

    private void button1_Click(object sender, EventArgs e)
     {
    
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.          
         if (result == DialogResult.OK) // Test result.
         {
             string file = openFileDialog1.FileName;
             using (Stream stream = File.OpenRead(file))
             {
                 byte[] buffer = new byte[stream.Length];
                 stream.Read(buffer, 0, buffer.Length);
                 string extn = new FileInfo(file).Extension;
                 string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (@Id,@FirstName,@LastName,@Email,@Password,@PdfFile,@FileExtn)";
    
                 List<SqlParameter> l = new List<SqlParameter>();
    
                 l.Add(new SqlParameter("@Id", "102"));
                 l.Add(new SqlParameter("@FirstName", "Aviv"));
                 l.Add(new SqlParameter("@LastName", "Halevy"));
                 l.Add(new SqlParameter("@Email", "Assadsa@gmail.com"));
                 l.Add(new SqlParameter("@Password", "123456"));
                 l.Add(new SqlParameter("@PdfFile", buffer));
                 l.Add(new SqlParameter("@FileExtn", extn));
                 if (DAL.Database.ParametersCommand(cmd, l) > 0)
                     textBox1.Text = "SUCCESS! Save with Stream";
             }
         }
     }
    

从流中写入文件:

   private void button2_Click(object sender, EventArgs e)
    {
        string cmd = "SELECT * FROM Employee WHERE ID = '102'";
        string path = "YOUR_PATH\\Test";
        DataTable dt = DAL.Database.GetDataTable(cmd);
        if (dt != null && dt.Rows.Count > 0)
        {
            Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
            string extn = dt.Rows[0]["FileExtn"].ToString();
            path = Path.Combine(path, "Test123"+extn);

            File.WriteAllBytes(path, file);
            Process.Start(path);
        }
    }

结果:

注意: 在我的示例中,DAL 项目有一个运行我的 sql 命令的静态方法。

【讨论】:

  • 我刚刚尝试使用包含 {byte[4903685]} 的字节数组的大型 pdf 文件并使用两种方法得到相同的结果。你能给我任何关于你所说的限制的参考吗?
  • tnx u @user9938 ,不知道。我现在已经确定了答案。
最近更新 更多