【问题标题】:C# and NpgsqlDataAdapter returning a single string instead of a data tableC# 和 NpgsqlDataAdapter 返回单个字符串而不是数据表
【发布时间】:2023-03-27 00:19:01
【问题描述】:

我有一个 postgresql 数据库和一个 C# 应用程序来访问它。我从 NpgsqlDataAdapter.Fill 命令返回到 DataSet 的值出现一个奇怪的错误。

我有这个代码:

NpgsqlCommand n = new NpgsqlCommand();
n.Connection = connector; // a class member NpgsqlConnection

DataSet ds = new DataSet();
DataTable dt = new DataTable();

// DBTablesRef are just constants declared for
// the db table names and columns

ArrayList cols = new ArrayList();
cols.Add(DBTablesRef.all); //all is just *

ArrayList idCol = new ArrayList();
idCol.Add(DBTablesRef.revIssID);

ArrayList idVal = new ArrayList();
idVal.Add(idNum); // a function parameter

// Select builder and Where builder are just small
// functions that return an sql statement based
// on the parameters.  n is passed to the where
// builder because the builder uses named  
// parameters and sets them in the NpgsqlCommand
// passed in
String select = SelectBuilder(DBTablesRef.revTableName, cols) +
WhereBuilder(n,idCol, idVal);

n.CommandText = select;

try
{
    NpgsqlDataAdapter da = new NpgsqlDataAdapter(n);

    ds.Reset();

    // filling DataSet with result from  NpgsqlDataAdapter
    da.Fill(ds);

    // C# DataSet takes multiple tables, but only the first is used here
    dt = ds.Tables[0];
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

所以我的问题是:上面的代码完美地工作,就像我想要的那样。但是,如果我尝试命名单个列以从查询中返回,而不是对所有 (*) 进行选择,我会得到我要求的信息,而不是在数据表中被拆分为单独的条目,我得到一个字符串在数据表的第一个索引中,看起来像:

"(0,5,false,鲍勃·史密斯,7)"

而且数据是正确的,我希望是 0,然后是 5,然后是布尔值,然后是一些文本等。但我(显然)更希望它不作为一个大字符串返回。

任何人都知道为什么如果我对 * 进行选择,我会按预期得到一个数据表,但如果我对特定列进行选择,我会得到一个数据表,其中一个条目是我要求的值的字符串?

【问题讨论】:

    标签: c# postgresql datatable npgsql


    【解决方案1】:

    好的,我想通了,它在 SelectBuilder 函数中。当 select 语句中列出了多个列时,它会将列包装在 () 中,显然这会导致 postgreSQL 或 Npgsql 将其解释为希望以字符串形式返回列表。

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多