【问题标题】:filling dataset using data adapter使用数据适配器填充数据集
【发布时间】:2014-07-02 01:39:18
【问题描述】:

我的代码如下。

SqlCommand command = new SqlCommand();
command.Parameters.AddWithValue("@AccountId", accountNumberLong);
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT * FROM T_POSTAGE_DISCOUNT");
sqlQuery = sql.ToString();

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    command.Connection = connection;
    command.CommandType = CommandType.Text;
    command.CommandText = sqlQuery;
    SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
    dataAdapter.Fill(dsDiscounts, "Discounts");
}

到目前为止,它工作正常。我想向这个数据集添加另一个表。然后我就这样了。

command.Parameters.AddWithValue("@DISCOUNT_LEVEL_NBR",discountLevelNBR);
sql.AppendLine("select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR");
sqlQuery = sql.ToString();
using (SqlConnection connection = new SqlConnection(connectionString))
{

    connection.Open();
    command.Connection = connection;
    command.CommandType = CommandType.Text;
    command.CommandText = sqlQuery;
    SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
    dataAdapter.Fill(dsDiscounts,"CONTRACT");

}

它再次添加所有表格。我想将 onlt 合同表添加到现有数据集。
我该怎么做?(c#)

【问题讨论】:

  • 我认为您正在再次附加查询“sql.AppendLine("select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR");”,因此当您第二次执行时,它会同时执行这两个.. .
  • 其实它是一个单独的查询。两个查询中的表名不同。我现在该怎么办?
  • 创建一个新的字符串生成器 StringBuilder sql1 = new StringBuilder();然后 sql1.AppendLine("select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR"); sqlQuery = sql1.ToString();
  • 看看这个link

标签: c# sql-server


【解决方案1】:

试试这个。

DataTable myTable = new DataTable("MyTable");
adapter.Fill(myTable);
ds.Tables.Add(myTable);

【讨论】:

  • 你能简单解释一下你的答案吗?
【解决方案2】:

问题出在您在字符串 sql 上执行了两次的附加行, 当你写sql.AppendLine("..."); 字符串 sql = "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR".

然后在另一行中,再次向字符串 sql 添加命令,使其变为
sql = "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR" "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR"
所以很清楚为什么它会再次带来所有桌子。
所以最好使用两个字符串 sql1 , sql2。

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2014-03-23
    • 2013-12-07
    • 2014-07-03
    • 2013-06-13
    • 2015-06-21
    • 2013-11-27
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多