【问题标题】:Create Json string by looping over DataTable rows通过循环遍历 DataTable 行来创建 Json 字符串
【发布时间】:2015-04-22 14:15:34
【问题描述】:

我需要从 SQL 查询创建一个 Json 字符串。我有一些处理静态数据的基本代码。现在我需要弄清楚如何遍历 DataTable 行并创建我的字符串列表。

string sql = "SELECT ID, FirstName, LastName";

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
SqlDataAdapter adapter = new SqlDataAdapter(sql, con);

DataTable dt = new DataTable();
adapter.Fill(dt);


return Json(new
{
    sEcho = param.sEcho,
    iTotalRecords = dt.Rows.Count,
    iTotalDisplayRecords = dt.Rows.Count,
    aaData = new List<string[]>() {
        new string[] {"4806", "Kenneth", "Sheffield"},
        new string[] {"3063", "Michael", "Harrison"},
        new string[] {"4000", "Jose", "Penalosa"}
    }
},

【问题讨论】:

标签: c# sql json loops foreach


【解决方案1】:

你可以这样提取数据:

foreach(DataRow row in dt.Rows)
{
    var id = row["ID"].ToString();
    var fname = row["FirstName"].ToString();
    var lname = row["LastName"].ToString();
}

【讨论】:

    【解决方案2】:

    下面的文章 Producing JSON Documents from SQL Server queries via TSQL 介绍了 SQL Server 中的这个过程。

    假设您有一个填充的DataTable 对象,您可以按如下方式遍历表的行(即DataRow 对象):

    var list = new List<string[]>();
    
    foreach(DataRow row in dt.Rows)
    {
        // This code sample could be collapsed further, but is not for this example.
        // Additionally, this sample does not include any validation or error-checking.
        string id = row["ID"].ToString();
        string firstName = row["FirstName"].ToString();
        string lastName = row["LastName"].ToString();
        // Validation & error-checking could go here before executing the Add() method.
        list.Add(new string[] {id, firstName, lastName});
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 2018-10-19
      • 2010-12-02
      • 1970-01-01
      • 2010-10-11
      • 2014-09-19
      • 2023-03-23
      相关资源
      最近更新 更多