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

e-m*_*tiv 6 .net c# sqlite

我一直在努力获得正确的c#代码,以便在PRAGMA table_info查询之后获取值.

由于我在这篇文章中使用额外代码进行了编辑,因此我向其他人提出了这个问题,否则会浪费数小时来快速解决问题.

Tob*_*bon 13

假设你想要一个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)
              { }
         }
     }
Run Code Online (Sandbox Code Playgroud)

返回结果是:

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

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

 return table.AsEnumerable().Select(r=>r["name"].ToString()).ToList();
Run Code Online (Sandbox Code Playgroud)

编辑:或者您可以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>();
Run Code Online (Sandbox Code Playgroud)

您可以在SQLite中使用很多PRAGMA语句,查看链接.

关于using声明:它非常简单,它用于确保一次性对象将被处置在您的代码中发生的任何事情:请参阅此链接此参考