c# - 如何通过 PRAGMA (.net/c#) 从 sqlite 中的表中获取列名?

标签 c# .net sqlite

我一直在努力寻找正确的 C# 代码来获取 PRAGMA table_info 查询后的值。

因为我使用额外代码的编辑在 this post 中被拒绝了,我为其他人提出了这个问题,否则他们会浪费时间来快速解决问题。

最佳答案

假设您想要一个包含表字段列表的DataTable:

 using (var con = new SQLiteConnection(preparedConnectionString))
    {
       using (var cmd = new SQLiteCommand("PRAGMA table_info(" + tableName + ");"))
        {
            var table = new DataTable();

            cmd.Connection = con;
            cmd.Connection.Open();

             SQLiteDataAdapter adp = null;
                try
                {
                    adp = new SQLiteDataAdapter(cmd);
                    adp.Fill(table);
                    con.Close();
                    return table;
                }
              catch (Exception ex)
              { }
         }
     }

返回结果为:

  • cid:列的id
  • name: 列名
  • type: 列的类型
  • notnull:如果列可以包含空值,则为 0 或 1
  • dflt_value:默认值
  • pk:如果列参与主键,则为 0 或 1

如果您只想将列名放入 List 中,您可以使用(您必须包含 System.Data.DataSetExtension):

 return table.AsEnumerable().Select(r=>r["name"].ToString()).ToList();

编辑:或者您可以使用以下代码避免 DataSetExtension 引用:

using (var con = new SQLiteConnection(preparedConnectionString))
      {
          using (var cmd = new SQLiteCommand("PRAGMA table_info(" + tableName + ");"))
          {
              var table = new DataTable();
              cmd.Connection = con;
              cmd.Connection.Open();

              SQLiteDataAdapter adp = null;
              try
              {
                  adp = new SQLiteDataAdapter(cmd);
                  adp.Fill(table);
                  con.Close();
                  var res = new List<string>();
                  for(int i = 0;i<table.Rows.Count;i++)
                      res.Add(table.Rows[i]["name"].ToString());
                  return res;
              }
              catch (Exception ex){ }
          }
      }
      return new List<string>();

有很多PRAGMA您可以在 SQLite 中使用的语句,请查看链接。

关于 using 语句:它非常简单,它用于确保无论您的代码中发生什么,一次性对象都将被释放:参见 this linkthis reference

关于c# - 如何通过 PRAGMA (.net/c#) 从 sqlite 中的表中获取列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17717829/

相关文章:

c# - 如何反序列化 JSON 并将其映射到字符串对象

c# - 简单的xml解析

.net - 带有 ListView 的 MVVM 按钮事件未获取所选项目

sql - 如何选择列值以特定字符串开头的行?

java - 如何在 android studio 中从 SQLite 检索图像

ios - 如何更改iOS中sql列的数据类型?

c# - 根据受欢迎程度选择项目 : Avoiding a glorified sort

c# - 错误: Assembly uses System. Web.Mvc,引用程序集的版本较高

c# - 是否应该将此列表初始值设定项行为报告为 Visual Studio C# 编译器中的错误?

c# - 在 WP8 中从 Web URL 加载图像