You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中使用WHERE条件过滤数据库表ID并导出至iTextSharp PDF

VB.NET实现按ID过滤数据库数据并导出PDF

原代码问题分析

  1. SQL参数@ID未赋值,WHERE过滤条件完全失效,查询无法返回指定ID的数据。
  2. 异常处理块为空,无法定位数据库连接、查询或PDF生成过程中的错误。
  3. PDF表格缺少字段表头,导出内容可读性差。

修正后的完整代码

Private Sub ExportFilteredDataToPdf(targetId As String)
    ' 创建PDF表格,设置列宽等属性
    Dim table As New PdfPTable(4)
    table.TotalWidth = 416.0F
    table.LockedWidth = False
    Dim widths As Single() = New Single() {1.0F, 2.0F, 3.0F, 4.0F}
    table.SetWidths(widths)
    table.HorizontalAlignment = 0
    table.SpacingBefore = 20.0F
    table.SpacingAfter = 30.0F

    ' 添加表格标题
    Dim titleCell As New PdfPCell(New Phrase("学生出勤记录"))
    titleCell.Colspan = 4
    titleCell.Border = 0
    titleCell.HorizontalAlignment = 1
    table.AddCell(titleCell)

    ' 添加表格表头
    table.AddCell(New Phrase("ID"))
    table.AddCell(New Phrase("姓名"))
    table.AddCell(New Phrase("班级"))
    table.AddCell(New Phrase("日期"))

    ' 数据库连接字符串
    Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"

    ' 使用Using确保资源自动释放
    Using conn As New SqlConnection(connect)
        Using pdfDoc As New Document()
            ' 确保PDF目录存在
            Dim pdfDir As String = "D:\pdf\"
            If Not Directory.Exists(pdfDir) Then
                Directory.CreateDirectory(pdfDir)
            End If
            Dim pdfPath As String = pdfDir & DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") & ".pdf"
            
            Using fs As New FileStream(pdfPath, FileMode.Create)
                Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, fs)
                pdfDoc.Open()

                ' 带参数的SQL查询语句
                Dim query As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM WHERE ID = @ID"
                Using cmd As New SqlCommand(query, conn)
                    ' 为参数赋值,这里的targetId是传入的目标ID
                    cmd.Parameters.AddWithValue("@ID", targetId)

                    Try
                        conn.Open()
                        Using rdr As SqlDataReader = cmd.ExecuteReader()
                            ' 读取查询结果并添加到PDF表格
                            While rdr.Read()
                                table.AddCell(rdr("ID").ToString())
                                table.AddCell(rdr("Name").ToString())
                                table.AddCell(rdr("Class").ToString())
                                ' 格式化日期显示,处理空值
                                table.AddCell(If(rdr("Date") Is DBNull.Value, "", Convert.ToDateTime(rdr("Date")).ToString("yyyy-MM-dd")))
                            End While
                        End Using
                    Catch ex As Exception
                        ' 捕获异常并提示,可替换为日志记录
                        MessageBox.Show($"执行出错:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try
                End Using

                pdfDoc.Add(table)
                pdfDoc.Close()
                MessageBox.Show($"PDF已导出至:{pdfPath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End Using
        End Using
    End Using
End Sub

关键修改说明

  • 参数赋值:通过cmd.Parameters.AddWithValue("@ID", targetId)为WHERE条件的参数指定具体值,既保证过滤生效,又避免SQL注入风险。
  • 完善资源管理:将FileStream、SqlCommand等资源用Using包裹,确保使用后自动释放,避免内存泄漏。
  • 添加表头与标题:补充表格的字段表头和标题,让导出的PDF内容更清晰。
  • 异常处理优化:捕获异常并弹出提示,方便调试和用户知晓执行状态。
  • 日期格式化:处理数据库中可能的空日期值,并将日期格式化为易读的字符串。
  • 目录检查:生成PDF前检查目标目录是否存在,不存在则创建,避免因目录缺失导致的错误。

内容的提问来源于stack exchange,提问作者bush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:15:45