【问题标题】:How to get columns' name from a table in sqlite3 database using python3?如何使用 python3 从 sqlite3 数据库中的表中获取列名?
【发布时间】:2021-05-16 01:26:11
【问题描述】:

我已经阅读了一些关于此的答案。但他们都给了我同样的错误。

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

  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)
    

表名是emplyee

错误是: Traceback(最近一次调用最后一次):

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

result = execute(cursor, command)

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

return cursor.execute(command)

sqlite3.OperationalError:靠近“.”:语法错误

【问题讨论】:

  • 您使用的是什么数据库?您标记了 MySQL 和 SQL Server,但代码指示 SQLite。
  • 我正在使用 SQLITE3,但我不知道它们是不同的。我认为基本命令必须相同

标签: python-3.x sqlite


【解决方案1】:

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 在这里做什么吗?
  • @AdarshMaurya 它阻止查询返回任何数据。
  • 表达式1=0 不适用于任何行。无论如何,SQLite 会按需计算结果行,因此不需要。
  • 1=0 的条件不会选择任何行,因为您没有尝试获取数据;您想要的只是光标对象中的表描述。浪费时间选择不需要的数据是没有意义的。
【解决方案2】:

做同样的事情,但语法更现代。 (你不需要在 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]

【讨论】:

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