如何使用python3从sqlite3数据库中的表中获取列的名称?

时间:2017-07-09 16:49:36

标签: python-3.x sqlite

我已经阅读了一些有关此问题的答案。但是他们所有人都给了我同样的错误。

以下是我读过的解决方案:

  1. Link 1
  2. Link 2

    import sqlite3 as sql
    
    #connect to database
    connection = sql.connect("database.db")
    
    #make a cursor which will move in the database
    cursor = connection.cursor()
    
    #execute the different command
    def execute(cursor, command):
        return cursor.execute(command)
    
    #print the result
    def print_result(result):
        for var in result:
            print(var)
    # select columns' name from table
    
    command = """select distinct emplyee from emplyee.information_schema.columns"""
    
    result = execute(cursor, command)
    print_result(result)
    
  3. 表名是 emplyee

    错误: 回溯(最近一次调用最后一次):

    文件“database.py”,第47行,

    result = execute(cursor, command)
    

    文件“database.py”,第11行,执行

    return cursor.execute(command)
    

    sqlite3.OperationalError:near“。”:语法错误

2 个答案:

答案 0 :(得分:2)

SQLite不支持information_schema,因此您需要执行以下操作:

def table_columns(db, table_name)
    curs = db.cursor()
    sql = "select * from %s where 1=0;" % table_name
    curs.execute(sql)
    return [d[0] for d in curs.description]

答案 1 :(得分:0)

做同样的事情,但使用更现代的语法。 (您不需要在 sqlite3 中使用带有 execute() 的游标。)

import sqlite3

def get_col_names(file_name: str, table_name: str) -> List[str]:
    conn = sqlist3.connect(file_name)
    col_data = conn.execute(f'PRAGMA table_info({table_name});').fetchall()
    return [entry[1] for entry in col_data]
相关问题