【问题标题】:How to get a list of column names如何获取列名列表
【发布时间】:2010-10-15 16:09:18
【问题描述】:

是否可以像这样获取包含表的所有列名的行?

|id|foo|bar|age|street|address|

我不喜欢使用Pragma table_info(bla)

【问题讨论】:

  • 出于好奇,为什么使用编译指示?
  • @Phil 因为那不值得你不能从返回的表中得到名字.. :(
  • 一个问题可能是您无法加入编译指示的结果。例如,如果您想在同一结果集中获取所有表名及其列。
  • @Phil 另外,你不能在 WebSQL 中使用 PRAGMA...
  • 根据具体情况,您可以考虑将 pragma table_info 的输出存储到单独的表中。

标签: sqlite


【解决方案1】:
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

然后用 Reg Exp 解析这个值(这很简单),看起来类似于:[(.*?)]

您也可以使用:

PRAGMA table_info(table_name)

【讨论】:

  • Then parse this value with Reg Exp (it's easy)... 真的很模糊,使用正则表达式查询列定义的完整示例在这里会有很长的路要走。
  • 我把这个留给下一个:这个正则表达式 "([^"]+)" (?!\() 似乎有效。
  • 这是否适用于获取 JOIN 查询返回的列的名称?我不这么认为。
  • 我正在使用的 Perl 正则表达式示例:“qr/\s (id) \s+ INTEGER \s+ PRIMARY \s KEY \s/msx”(“qr/”和“/msx”是Perl-y 位用于声明为处理多行字符串“ms”并允许嵌入 cmets“x”的正则表达式。
【解决方案2】:
$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
  echo "Column: $column  Type: $type\n";
}

【讨论】:

    【解决方案3】:

    这有助于 HTML5 SQLite:

    tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
      var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
      var columnNames = [];
      for(i in columnParts) {
        if(typeof columnParts[i] === 'string')
          columnNames.push(columnParts[i].split(" ")[0]);
      }
      console.log(columnNames);
      ///// Your code which uses the columnNames;
    });
    

    您可以在您的语言中重复使用正则表达式来获取列名。

    较短的替代方案:

    tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
      var columnNames = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').replace(/ [^,]+/g, '').split(',');
      console.log(columnNames);
      ///// Your code which uses the columnNames;
    });
    

    【讨论】:

    • 请注意,这两种解决方案都假定 SQLITE_MASTER 表的 sql 字段中没有任何额外的空格或其他空格。由于此字段包含用于创建表的文字查询文本,因此并非总是如此。我还认为它无法正确处理包含空格的字段名称。
    • 很好的解决方案。我担心这不会包括后续的列更改,但是,根据规范,“sql”列包含“创建对象的原始 CREATE 语句文本的副本,除了如上所述的规范化和后续的 ALTER TABLE 修改声明。”。
    【解决方案4】:

    使用@Tarkus 的答案,这是我在 R 中使用的正则表达式:

    getColNames <- function(conn, tableName) {
        x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
        x <- str_split(x,"\\n")[[1]][-1]
        x <- sub("[()]","",x)
        res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
        x <- x[-1]
        x <- x[-length(x)]
        res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
        res
    }
    

    代码有些草率,但似乎可以工作。

    【讨论】:

      【解决方案5】:

      如果您使用 SQLite 的命令行 shell,则在执行查询之前.headers on。您只需在给定会话中执行一次。

      【讨论】:

      • 对于那些想要获得他们习惯于在其他 SQL shell 中看到的典型 SELECT 输出格式的人来说,同时使用 .mode column.headers on
      【解决方案6】:

      PHP 中的查询结果集提供了几个函数:

          numCols() 
          columnName(int $column_number )
      

      例子

          $db = new SQLIte3('mysqlite.db');
          $table = 'mytable';
      
          $tableCol = getColName($db, $table);
      
          for ($i=0; $i<count($tableCol); $i++){
              echo "Column $i = ".$tableCol[$i]."\n";
          }           
      
          function getColName($db, $table){
              $qry = "SELECT * FROM $table LIMIT 1";
              $result = $db->query($qry);
              $nCols = $result->numCols();
              for ($i = 0; $i < $ncols; $i++) {
                  $colName[$i] = $result->columnName($i);
              }
              return $colName;
          }
      

      【讨论】:

        【解决方案7】:

        试试这个 sqlite 表模式解析器,我实现了 sqlite 表解析器来解析 PHP 中的表定义。

        它返回完整的定义(唯一、主键、类型、精度、非空、引用、表约束...等)

        https://github.com/maghead/sqlite-parser

        【讨论】:

          【解决方案8】:

          获取最近执行的 SELECT 的列名的最简单方法是使用游标的 description 属性。一个 Python 示例:

          print_me = "("
          for description in cursor.description:
              print_me += description[0] + ", "
          print(print_me[0:-2] + ')')
          # Example output: (inp, output, reason, cond_cnt, loop_likely)
          

          【讨论】:

            【解决方案9】:

            是的,您可以使用以下命令来实现:

            sqlite> .headers on
            sqlite> .mode column
            

            在您的表上进行选择的结果将如下所示:

            id          foo         bar         age         street      address
            ----------  ----------  ----------  ----------  ----------  ----------
            1           val1        val2        val3        val4        val5
            2           val6        val7        val8        val9        val10
            

            【讨论】:

              【解决方案10】:

              使用递归查询。给定

              create table t (a int, b int, c int);
              

              运行:

              with recursive
                a (cid, name) as (select cid, name from pragma_table_info('t')),
                b (cid, name) as (
                  select cid, '|' || name || '|' from a where cid = 0
                  union all
                  select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
                )
              select name
              from b
              order by cid desc
              limit 1;
              

              或者,只需使用group_concat:

              select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')
              

              两者都有:

              |a|b|c|
              

              【讨论】:

                【解决方案11】:

                您可以在 sqlite 中使用 pragma 相关的命令,如下所示

                pragma table_info("table_name")
                --Alternatively
                select * from pragma_table_info("table_name")
                

                如果您需要像id|foo|bar|age|street|address 这样的列名,基本上您的答案在下面的查询中。

                select group_concat(name,'|') from pragma_table_info("table_name")
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-09-28
                  • 2013-01-27
                  • 2017-08-14
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-05-02
                  相关资源
                  最近更新 更多