【问题标题】:How to get a list of column names on Sqlite3 database?如何获取 Sqlite3 数据库上的列名列表?
【发布时间】:2010-10-31 03:20:04
【问题描述】:

我想将我的 iPhone 应用程序迁移到新的数据库版本。由于我没有保存某些版本,因此我需要检查某些列名是否存在。

这个Stackoverflow entry 建议进行选择

SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

并解析结果。

这是常见的方式吗?替代品?

【问题讨论】:

标签: sqlite


【解决方案1】:
PRAGMA table_info(table_name);

将为您提供所有列名的列表。

【讨论】:

  • 但您无法从该表中进行选择。这很烦人。我正在尝试这样的事情......但它不起作用create temporary table TmpCols (cid integer, name text, type text, nn bit, dflt_value, pk bit); .mode insert TmpCols .output cols PRAGMA TABLE_INFO('yourtable'); .read cols .mode csv .output stdout
  • 只是为了把它放到Android上SQLiteDatabase的代码术语中,写db.rawQuery("PRAGMA table_info(" + tablename + ")", null);
  • 这也适用于 View。 PRAGMA table_info(View_Name);这将列出视图的所有列
  • 为什么不在选择语句的末尾加上“limit 0”? int cols = sqlite3_column_count(stmt); fprintf(stdout, "%d 列\n", cols); for (int i=0; i
  • 要作为查询执行,请参阅@user1461607 中的answerselect * from pragma_table_info('tblName') as tblInfo;
【解决方案2】:

如果你有 sqlite 数据库,使用 sqlite3 命令行程序和这些命令:

列出数据库中的所有表:

.tables

显示给定tablename 的架构:

.schema tablename

【讨论】:

  • 虽然输出不那么“可读”(也许)这比PRAGMA table_info(table_name);更容易记住
  • @NickTomlin 不幸的是,这种方法需要使用 sqlite3 命令行程序,因为点命令不是有效的 SQL。
【解决方案3】:

如果你这样做

.headers ON

你会得到想要的结果。

【讨论】:

  • 如何将标题与下面的内容对齐?
  • 如果要一直使用它,请将其放入your .sqliterc file
  • 这是否适用于空表?我仍然没有看到列名
  • 由于某些我不知道的原因,PRAGMA 方法和.schema 方法都不适用于我。但是这个工作得很好。
  • .headers on.mode columns 将打开列名并对齐所有内容
【解决方案4】:

只适合像我这样想知道人们的意思或含义的超级菜鸟

PRAGMA table_info('table_name') 

您想使用它作为您的准备语句,如下所示。这样做会选择一个看起来像这样的表,除了填充了与您的表相关的值。

cid         name        type        notnull     dflt_value  pk        
----------  ----------  ----------  ----------  ----------  ----------
0           id          integer     99                      1         
1           name                    0                       0

其中 id 和 name 是列的实际名称。因此,要获得该值,您需要使用以下方法选择列名:

//returns the name
sqlite3_column_text(stmt, 1);
//returns the type
sqlite3_column_text(stmt, 2);

这将返回当前行的列名。要全部获取它们或找到您想要的,您需要遍历所有行。最简单的方法是采用以下方式。

//where rc is an int variable if wondering :/
rc = sqlite3_prepare_v2(dbPointer, "pragma table_info ('your table name goes here')", -1, &stmt, NULL);

if (rc==SQLITE_OK)
{
    //will continue to go down the rows (columns in your table) till there are no more
    while(sqlite3_step(stmt) == SQLITE_ROW)
    {
        sprintf(colName, "%s", sqlite3_column_text(stmt, 1));
        //do something with colName because it contains the column's name
    }
}

【讨论】:

  • 他们的意思是执行sqlite3(或为您命名的任何名称)进入sqlite CLI,然后输入该文本。无需为此编写大量代码:)
  • 是的,正如@Xerus 所说...不需要大量代码。直接使用sqlite3即可。此外,@birdbuster,它有助于指定您正在使用的语言和库。在我看来,它看起来像 C++(来自 sprintf 函数)。澄清一下会很有帮助,因为 OP 问题与语言无关。
【解决方案5】:

如果您希望查询的输出包含列名并正确对齐为列,请在sqlite3 中使用这些命令:

.headers on
.mode column

你会得到如下输出:

sqlite> .headers on
sqlite> .mode column
sqlite> select * from mytable;
id          foo         bar
----------  ----------  ----------
1           val1        val2
2           val3        val4

【讨论】:

  • 哇!!!我不知道.mode column。多么强大的工具,可以快速以交互方式快速可视化和调试数据!谢谢!! :-) +1!
  • 这很有帮助,恕我直言,这最终应该被接受!
  • 来自未来的评论,只是说这太棒了。我想在 postgres 上使用 sqlite,但是没有列名并且与值对齐对我来说是不行的。但现在,它就像 postgres 或 mysql 一样工作。
【解决方案6】:

获取此处未提及的列名列表的另一种方法是跨平台且不依赖于 sqlite3.exe shell,是从 PRAGMA_TABLE_INFO() 表值函数中进行选择。

SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name      
tbl_name  
rootpage  
sql

可以通过查询来检查某列是否存在:

SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='column1';
1

如果您不想从 sqlite_master 或 pragma table_info 解析 select sql 的结果,则使用此方法。

请注意,此功能是实验性的,是在 SQLite 版本 3.16.0 (2017-01-02) 中添加的。

参考:

https://www.sqlite.org/pragma.html#pragfunc

【讨论】:

  • 不错的干净方法。在此之前我不知道 PRAGMA 函数。谢谢。
  • 非常有用的sn-p,我在自己的代码中用过一次。感谢分享!! :-) 另外,我不知道PRAGMA;感谢您的示例和链接! +1!!
  • 这应该是公认的答案,因为这允许使用结果。此外,它还包含更改的数据。
  • 这仅适用于本地数据库。如果您尝试使用附加的架构,它将无法正常工作。
【解决方案7】:

要获取列列表,您可以简单地使用:

.schema tablename

【讨论】:

  • 这不会显示使用 ALTER 语句添加的列。
【解决方案8】:

我知道这是一个旧线程,但最近我需要它并找到了一个简洁的方法:

SELECT c.name FROM pragma_table_info('your_table_name') c;

【讨论】:

  • 你的意思是:where t.name = 'table';
  • 您是否从我的回答中找到了巧妙的方法? ?
【解决方案9】:

当您运行 sqlite3 cli 时,输入:

sqlite3 -header

也会给出想要的结果

【讨论】:

    【解决方案10】:

    .schema table_name

    这将列出数据库中表的列名。

    希望这会有所帮助!!!

    【讨论】:

      【解决方案11】:

      如果您正在搜索任何特定列,您可以使用 Like 语句

      例如:

      SELECT * FROM sqlite_master where sql like('%LAST%')
      

      【讨论】:

        【解决方案12】:

        为了获取列信息可以使用下面的sn-p:

        String sql = "select * from "+oTablename+" LIMIT 0";
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        ResultSetMetaData mrs = rs.getMetaData();
        for(int i = 1; i <= mrs.getColumnCount(); i++)
        {
            Object row[] = new Object[3];
            row[0] = mrs.getColumnLabel(i);
            row[1] = mrs.getColumnTypeName(i);
            row[2] = mrs.getPrecision(i);
        }
        

        【讨论】:

        • 这适用于视图、连接等——但这是什么 db 包装器?
        • 简直就是jdbc。没有包装。
        • jdbc 是一个包装器 ;)
        【解决方案13】:
        //JUST little bit modified the answer of giuseppe  which returns array of table columns
        +(NSMutableArray*)tableInfo:(NSString *)table{
        
            sqlite3_stmt *sqlStatement;
        
            NSMutableArray *result = [NSMutableArray array];
        
            const char *sql = [[NSString stringWithFormat:@"PRAGMA table_info('%@')",table] UTF8String];
        
            if(sqlite3_prepare(md.database, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
        
            {
                NSLog(@"Problem with prepare statement tableInfo %@",
                        [NSString stringWithUTF8String:(const char *)sqlite3_errmsg(md.database)]);
        
            }
        
            while (sqlite3_step(sqlStatement)==SQLITE_ROW)
            {
                [result addObject:
                  [NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
            }
        
            return result;
        }
        

        【讨论】:

          【解决方案14】:

          .schema 当您在桌子内时,在 sqlite 控制台中 对我来说它看起来像这样......

          sqlite>.schema
          CREATE TABLE players(
          id integer primary key,
          Name varchar(255),
          Number INT,
          Team varchar(255)
          

          【讨论】:

            【解决方案15】:
            function getDetails(){
            var data = [];
            dBase.executeSql("PRAGMA table_info('table_name') ", [], function(rsp){
                if(rsp.rows.length > 0){
                    for(var i=0; i<rsp.rows.length; i++){
                        var o = {
                            name: rsp.rows.item(i).name,
                            type: rsp.rows.item(i).type
                        } 
                        data.push(o);
                    }
                }
                alert(rsp.rows.item(0).name);
            
            },function(error){
                alert(JSON.stringify(error));
            });             
            }
            

            【讨论】:

            • 嘿,我认为问题是关于 SQLite CLI。请添加至少一个解释。
            【解决方案16】:
            -(NSMutableDictionary*)tableInfo:(NSString *)table
            {
              sqlite3_stmt *sqlStatement;
              NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
              const char *sql = [[NSString stringWithFormat:@"pragma table_info('%s')",[table UTF8String]] UTF8String];
              if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
              {
                NSLog(@"Problem with prepare statement tableInfo %@",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]);
            
              }
              while (sqlite3_step(sqlStatement)==SQLITE_ROW)
              {
                [result setObject:@"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
            
              }
            
              return result;
              }
            

            【讨论】:

              【解决方案17】:

              我知道为时已晚,但这会对其他人有所帮助。

              要找到表的列名,你应该执行select * from tbl_name,你会得到sqlite3_stmt *的结果。并检查列迭代总提取列。请参考以下代码。

              // sqlite3_stmt *statement ;
              int totalColumn = sqlite3_column_count(statement);
              for (int iterator = 0; iterator<totalColumn; iterator++) {
                 NSLog(@"%s", sqlite3_column_name(statement, iterator));
              }
              

              这将打印结果集的所有列名。

              【讨论】:

              • 嘿,我认为问题是关于 SQLite CLI。您应该提及您使用的是哪种语言 - 这是纯 C 语言吗?
              【解决方案18】:

              如果一切都失败了,您可以随时提交查询,将返回行限制为无:

              select * from MYTABLENAME limit 0
              

              【讨论】:

              • 使用 sqlite3 不会产生任何输出
              【解决方案19】:
                   //Called when application is started. It works on Droidscript, it is tested
                   function OnStart()
                   {
                   //Create a layout with objects vertically centered. 
                   lay = app.CreateLayout( "linear", "VCenter,FillXY" );  
              
                   //Create a text label and add it to layout.
                   txt = app.CreateText( "", 0.9, 0.4, "multiline" )  
                   lay.AddChild( txt );
                   app.AddLayout(lay);
              
                   db = app.OpenDatabase( "MyData" )  
                
                   //Create a table (if it does not exist already).  
                   db.ExecuteSql( "drop table if exists test_table" )
                   db.ExecuteSql( "CREATE TABLE IF NOT EXISTS test_table " +  
                     "(id integer primary key, data text, num integer)",[],null, OnError )  
                      db.ExecuteSql( "insert into test_table values (1,'data10',100), 
                      (2,'data20',200),(3,'data30',300)")
                      //Get all the table rows.      
                      DisplayAllRows("SELECT * FROM test_table");
                      DisplayAllRows("select *, id+100 as idplus, 'hahaha' as blabla from 
                      test_table order by id desc;") 
                   }
              
              //function to display all records 
              function DisplayAllRows(sqlstring)  // <-- can you use for any table not need to 
                                              //  know column names, just use a *
                                              // example: 
              { 
              //Use all rows what is in ExecuteSql  (try any, it will works fine)
              db.ExecuteSql( sqlstring, [], OnResult, OnError ) 
              } 
              //Callback to show query results in debug.  
              function OnResult( res )   
              {  
              var len = res.rows.length; 
              var s = txt.GetText();  
              // ***********************************************************************
              // This is the answer how to read column names from table:
              for(var ColumnNames in res.rows.item(0)) s += " [ "+ ColumnNames +" ] "; // "[" & "]" optional, i use only in this demo 
              // ***********************************************************************
              //app.Alert("Here is all Column names what Select from your table:\n"+s);
              s+="\n";
              for(var i = 0; i < len; i++ )   
              {  
                  var rows = res.rows.item(i) 
                  for (var item in rows) 
                      {
                          s += "    " + rows[item] + "   ";
                      }
                  s+="\n\n";
              } 
              //app.Alert(s);
              txt.SetText( s )  
              }  
              //Callback to show errors.  
              function OnError( msg )   
              {  
                 app.Alert( "Error: " + msg )  
              }  
              

              【讨论】:

              • 这个答案太长而且过于冗长,而不是发布代码,请添加更多关于如何以及为什么为用户提供解决方案的详细信息,以便无需阅读和理解先解析
              • 嗨,我只是想分享我的想法,因为我之前没有完全解决我的同样问题。有 DroidScript 的演示。够了,谢谢,或者如果你愿意,我会删除我的共享。对不起我的英语。
              • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
              【解决方案20】:

              如果您使用的是 SQLite3,则不支持 INFORMATION_SCHEMA。请改用 PRAGMA table_info。这将返回有关该表的 6 行信息。要获取列名 (row2),请使用如下的 for 循环

              cur.execute("PRAGMA table_info(table_name)")  # fetches the 6 rows of data
              records = cur.fetchall() 
              print(records)
              for row in records:
                  print("Columns: ", row[1])
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2013-10-16
                • 1970-01-01
                • 1970-01-01
                • 2010-10-10
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多