【问题标题】:How can I use results from query in c# script in visual studio如何在 Visual Studio 的 C# 脚本中使用查询结果
【发布时间】:2018-07-17 11:35:16
【问题描述】:

我想在 Visual Studio 中的 C# 脚本中运行查询并在我的 C# 代码中使用结果(我基本上想要做的是将查询结果存储在表中并使用该表中的元素一个)。

查询在我的 C# 脚本中如下所示:

string Connection_sheets = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;

using (SqlConnection connection = new SqlConnection(Connection_sheets))
{
    connection.Open();

    SqlCommand cmd = new SqlCommand("select distinct [Sheet Code] from cell where [Table Code] = 'Table Number' order by [Sheet Code] asc", connection);
    SqlDataReader readert = cmd.ExecuteReader();
 }

这里的“表号”是一个字符串,它来自另一个数据库表中的列。

在以下放置在 for 循环中的代码中,我想添加另一列,每次从结果查询中打印一个元素

DataRow newRow2 = _longDataTable.NewRow();
newRow2.ItemArray = drlibrary.ItemArray;

newRow2["VariableTableCode"] = tableName;
newRow2["VariableRowCode"] = ssRowNoBars;
newRow2["VariableColumnCode"] = ssColumnNoBars;

_longDataTable.Rows.Add(newRow2);

有人知道怎么做吗?

【问题讨论】:

  • 有什么问题?
  • 需要更多细节在这里 mate + 把你的完整方法放在 1 代码 sn-p 中。拆分它很难理解你的问题..
  • 两个数据表是否属于同一个数据库?
  • 抱歉问题不清楚。更多详细信息:我可以运行查询并返回例如 G1、G2、G3 和 G4。现在我想使用 DataRow newRow2 将这些值添加到不同表中的新列中,每个列在单独的行中。
  • 我要添加值的表是使用 for 循环中的 newRow2 数据行创建的

标签: c# sql visual-studio


【解决方案1】:

在你的 using 语句中添加

While(reader.read()){

DataRow datarow3= _longDataTable.NewRow();
  datarow3.ItemArray = drlibrary.ItemArray;

   datarow3["VariableTableCode"] = reader.tostring(0);
   datarow3["VariableRowCode"] = reader.tostring(1);
   datarow4["VariableColumnCode"] = reader.tostring(2);

    _longDataTable.Rows.Add(datarow3);
       // you may need to encrement the row name variable. 

   }

【讨论】:

  • 这会在给定的三个列中打印查询结果,对吗?我希望这些列保持不变并具有 ssRowNoBars 和 ssColumnNoBars 值,因为这些值是使用巨大的 if 语句生成的。我想在此处添加另一列包含查询结果的列
  • 您能否解释一下 reader.tostring 中的 0、1 和 2 索引
  • 所以0,1,2是每一行的列索引。因此,对于每一行,它都会获得项目 1,2,3.. 等等。它是 0 索引。要添加一个新列,您只需要添加另一个 reader.tostring() 行。鉴于数据库有另一列。否则明确定义它
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多