sourcecode

SQLite3 데이터베이스에서 열 이름 목록을 가져오려면 어떻게 해야 합니까?

codebag 2023. 4. 23. 10:20
반응형

SQLite3 데이터베이스에서 열 이름 목록을 가져오려면 어떻게 해야 합니까?

iPhone 앱을 새 데이터베이스 버전으로 마이그레이션하고 싶습니다.저장된 버전이 없기 때문에 특정 열 이름이 있는지 확인해야 합니다.

Stackoverflow 엔트리는 select를 실행할 것을 권장합니다.

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

결과를 해석합니다.

그게 일반적인 방법인가요?다른 방법?

PRAGMA table_info(table_name);

그러면 모든 열 이름 목록이 나타납니다.

네가 한다면.

.headers ON

원하는 결과를 얻을 수 있습니다.

sqlite 데이터베이스가 있는 경우 sqlite3 명령줄 프로그램과 다음 명령을 사용합니다.

데이터베이스 내의 모든 테이블을 나열하려면:

.tables

tablename:

.schema tablename

나 같은 슈퍼노브들이 사람들이 무슨 말을 하는지 궁금해 하는 걸 보면

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:

.headers on
.mode column

다음과 같은 출력이 표시됩니다.

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

여기서 언급되지 않은 다른 방법으로 sqlite3에 의존하지 않는 크로스 플랫폼 열 이름 목록을 가져올 수 있습니다.exe 셸은 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

열 목록을 가져오려면 다음을 사용하십시오.

.schema tablename

「 」를 하고 sqlite3 cli, "cli" :

sqlite3 -header

원하는 결과도 얻을 수 있습니다.

오래된 실이라는 것은 알지만, 최근에는 같은 실이 필요해서 깔끔한 방법을 찾았습니다.

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

.schema table_name

그러면 데이터베이스의 테이블 열 이름이 나열됩니다.

도움이 되길 바랍니다!!!

특정 열을 검색하는 경우 Like 문을 사용할 수 있습니다.

예:

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

다음 명령어는 열 이름을 설정합니다.

.header on

그러면 다음과 같이 표시됩니다.

sqlite> select * from user;
id|first_name|last_name|age
1|Steve|Jobs|56
2|Bill|Gates|66
3|Mark|Zuckerberg|38

다음 명령어는 열 이름 설정을 해제합니다.

.header off

그러면 다음과 같이 표시됩니다.

sqlite> select * from user;
1|Steve|Jobs|56
2|Bill|Gates|66
3|Mark|Zuckerberg|38

다음 명령어는 ".header" 명령어에 대한 자세한 내용을 보여줍니다.

.help .header

또는 다음 중 하나를 선택합니다.

.help header

그러면 다음과 같이 표시됩니다.

sqlite> .help .header
.headers on|off          Turn display of headers on or off

또한 아래 명령은 출력 모드 "상자"설정합니다.

.mode box

그러면 다음과 같이 표시됩니다.

sqlite> select * from user;
┌────┬────────────┬────────────┬─────┐
│ id │ first_name │ last_name  │ age │
├────┼────────────┼────────────┼─────┤
│ 1  │ Steve      │ Jobs       │ 56  │
│ 2  │ Bill       │ Gates      │ 66  │
│ 3  │ Mark       │ Zuckerberg │ 38  │
└────┴────────────┴────────────┴─────┘

그리고 다음 명령은 출력 모드 "테이블"설정합니다.

.mode table

그러면 다음과 같이 표시됩니다.

sqlite> select * from user;
+----+------------+------------+-----+
| id | first_name | last_name  | age |
+----+------------+------------+-----+
| 1  | Steve      | Jobs       | 56  |
| 2  | Bill       | Gates      | 66  |
| 3  | Mark       | Zuckerberg | 38  |
+----+------------+------------+-----+

다음 명령어는 ".mode" 명령어에 대한 자세한 내용을 보여줍니다.

.help .mode

또는 다음 중 하나를 선택합니다.

.help mode

그러면 다음과 같이 표시됩니다.

sqlite> .help .mode
.import FILE TABLE       Import data from FILE into TABLE
   Options:
     --ascii               Use \037 and \036 as column and row separators
     --csv                 Use , and \n as column and row separators
     --skip N              Skip the first N rows of input
     --schema S            Target table to be S.TABLE
     -v                    "Verbose" - increase auxiliary output
   Notes:
     *  If TABLE does not exist, it is created.  The first row of input
        determines the column names.
     *  If neither --csv or --ascii are used, the input mode is derived
        from the ".mode" output mode
     *  If FILE begins with "|" then it is a command that generates the
        input text.
.mode MODE ?OPTIONS?     Set output mode
   MODE is one of:
     ascii       Columns/rows delimited by 0x1F and 0x1E
     box         Tables using unicode box-drawing characters
     csv         Comma-separated values
     column      Output in columns.  (See .width)
     html        HTML <table> code
     insert      SQL insert statements for TABLE
     json        Results in a JSON array
     line        One value per line
     list        Values delimited by "|"
     markdown    Markdown table format
     qbox        Shorthand for "box --width 60 --quote"
     quote       Escape answers as for SQL
     table       ASCII-art table
     tabs        Tab-separated values
     tcl         TCL list elements
   OPTIONS: (for columnar modes or insert mode):
     --wrap N       Wrap output lines to no longer than N characters
     --wordwrap B   Wrap or not at word boundaries per B (on/off)
     --ww           Shorthand for "--wordwrap 1"
     --quote        Quote output text as SQL literals
     --noquote      Do not quote output text
     TABLE          The name of SQL table used for "insert" mode

열 정보를 얻으려면 다음 스니펫을 사용합니다.

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);
}

오래된 질문이지만 SQLite 데이터베이스 내의 모든 컬럼과 각 컬럼에 관련된 테이블의 이름을 취득하는 대체 답변을 다음에 제시하겠습니다.

WITH tables AS (SELECT name tableName, sql 
FROM sqlite_master WHERE type = 'table' AND tableName NOT LIKE 'sqlite_%')
SELECT fields.name, fields.type, tableName
FROM tables CROSS JOIN pragma_table_info(tables.tableName) fields

그러면 다음 유형의 결과가 반환됩니다.

{
    "name": "id",
    "type": "integer",
    "tableName": "examples"
}, {
    "name": "content",
    "type": "text",
    "tableName": "examples"
}

식별자 및 문자열 내용을 포함하는 단순한 테이블.

//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;
}

sqlite 콘솔의 .display를 테이블 안에 배치하면 다음과 같이 됩니다.

sqlite>.schema
CREATE TABLE players(
id integer primary key,
Name varchar(255),
Number INT,
Team varchar(255)
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));
});             
}
-(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;
  }

늦은 건 알지만 이건 다른 사람에게 도움이 될 거야.

열 을 실행해야 .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));
}

결과 세트의 모든 열 이름이 인쇄됩니다.

하나의 sql 쿼리를 사용하여 해당 열이 있는 테이블 이름을 검색할 수 있었지만 열 출력이 쉼표로 구분되어 있습니다.도움이 됐으면 좋겠다

SELECT tbl_name, (SELECT GROUP_CONCAT(name, ',') FROM PRAGMA_TABLE_INFO(tbl_name)) as columns FROM sqlite_schema WHERE type = 'table';

테이블 및 열 목록을 보기로 가져옵니다.

CREATE VIEW Table_Columns AS
SELECT m.tbl_name AS TableView_Name, m.type AS TableView, cid+1 AS Column, p.*
FROM sqlite_master m, Pragma_Table_Info(m.tbl_name) p
WHERE m.type IN ('table', 'view') AND
   ( m.tbl_name = 'mypeople' OR m.tbl_name LIKE 'US_%')   -- filter tables
ORDER BY m.tbl_name;
     //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 )  
}  

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])

sqlite3와 함께 Python에서 사용

★★★★ PRAGMA table_info()는 추가 처리에 적합하지 않을 수 있는 다음과 같은 튜플 목록을 반환합니다.

[(0, 'id', 'INTEGER', 0, None, 0),
 (1, 'name', 'TEXT', 0, None, 0),
 (2, 'age', 'INTEGER', 0, None, 0),
 (3, 'profession', 'TEXT', 0, None, 0)]

Python에서 sqlite3를 사용할 때는 마지막에 목록 이해만 추가하면 불필요한 정보를 걸러낼 수 있습니다.

import sqlite3 as sq

def col_names(t_name):
    with sq.connect('file:{}.sqlite?mode=ro'.format(t_name),uri=True) as conn:
        cursor = conn.cursor()
        cursor.execute("PRAGMA table_info({}) ".format(t_name))
        data = cursor.fetchall()
        return [i[1] for i in data]

col_names("your_table_name")

결과

["id","name","age","profession"]

면책사항: 이 스니펫은 SQL 주입의 대상이 되므로 프로덕션에서 사용하지 마십시오.

언급URL : https://stackoverflow.com/questions/947215/how-to-get-a-list-of-column-names-on-sqlite3-database

반응형