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

不使用DataSet将SQL数据库数据写入自定义格式XML文件的问题

实现方案

你可以使用SqlCommand的ExecuteScalar方法直接获取单条查询结果(你的SQL仅返回单个City字段的单条记录,用该方法性能最优,无需引入DataSet或DataReader),修改后的完整代码如下:

Try
    Dim xmlfile As String = "path+name"
    If IO.File.Exists(xmlfile) Then
        IO.File.Delete(xmlfile)
    End If
    Dim enc As New System.Text.UTF8Encoding
    ' 用Using包裹Xml写入器,执行完毕自动释放资源
    Using XMLbg As New Xml.XmlTextWriter(xmlfile, enc)
        With XMLbg
            .Formatting = Xml.Formatting.Indented
            .Indentation = 4
            .WriteStartDocument()
            .WriteStartElement("Data")              
            
            ' --------------- 新增查询逻辑开始 ----------------
            Dim cityValue As String = String.Empty
            ' 用Using包裹数据库连接,执行完毕自动关闭释放
            Using connection As New SqlConnection(connetionString)
                connection.Open()
                Dim sql As String = "SELECT City FROM info WHERE No = '1'"
                Using cmd As New SqlCommand(sql, connection)
                    Dim result As Object = cmd.ExecuteScalar()
                    ' 处理数据库字段为空的情况
                    If Not IsDBNull(result) Then
                        cityValue = result.ToString()
                    End If
                End Using
            End Using
            ' 写入查询到的City值
            .WriteElementString("City", cityValue)
            ' --------------- 新增查询逻辑结束 ----------------
     
            .WriteEndElement() 'Data
        End With
    End Using
Catch ex As Exception
    MessageBox.Show(ex.Message.ToString(), "Exception ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

关键说明

  • ExecuteScalar适合仅返回单个值的查询场景,比DataReader、DataSet的资源开销更低
  • 所有涉及非托管资源的对象(SqlConnection、SqlCommand、XmlTextWriter)都用Using语句包裹,无需手动调用Close方法,避免资源泄漏
  • 增加了DBNull判断逻辑,避免数据库中City字段为空时出现类型转换报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:09:06