gpt4 book ai didi

c# - 读取 SQL 到 DataSet 到 XmlDocument

转载 作者:数据小太阳 更新时间:2023-10-29 02:58:12 27 4
gpt4 key购买 nike

下面的代码非常棒。但它可以变得更紧凑和 C# 风格吗?我尤其怀疑两个问题。

  1. 通过将变量用作输入参数来填充 fill 变量(旧 C 风格)不是很丑吗?
  2. 能否使代码更紧凑而不是通过 String

C#

String
connectionString = "...",
sqlStatement = "select * from Test",
output = "";

SqlDataAdapter adapter = new SqlDataAdapter(sqlStatement, connectionString);
DataSet dataSet = new DataSet("Contents");
adapter.Fill(dataSet, "Test");
StringWriter stringWriter=new StringWriter();
dataSet.WriteXml(new XmlTextWriter(stringWriter));
XmlDocument document = new XmlDocument();
output = stringWriter.ToString();
document.LoadXml(output);

最佳答案

我不知道如何让它更像 C# 或更紧凑,但你确实需要关闭你的适配器和 StringWriter。我会使用 using block 。

   String
connectionString = "...",
sqlStatement = "select * from Test",
output = "";

DataSet dataSet = new DataSet("Contents");
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStatement, connectionString)){
adapter.Fill(dataSet, "Test");}
using (StringWriter stringWriter = new StringWriter()) {
dataSet.WriteXml(new XmlTextWriter(stringWriter));
output = stringWriter.ToString();
};
XmlDocument document = new XmlDocument();
document.LoadXml(output);

关于c# - 读取 SQL 到 DataSet 到 XmlDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com