Adarsh Maurya
Adarsh Maurya

Reputation: 358

How to get columns' name from a table in sqlite3 database using python3?

I already have read some answers on this. But all of them are giving me the same error.

Here are the solutions I read:

  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)
    

The table name is emplyee.

Error is: Traceback (most recent call last):

File "database.py", line 47, in

result = execute(cursor, command)

File "database.py", line 11, in execute

return cursor.execute(command)

sqlite3.OperationalError: near ".": syntax error

Upvotes: 2

Views: 11433

Answers (2)

rbasham
rbasham

Reputation: 241

Does the same thing but with more modern syntax. (You don't need to use cursors with execute() in sqlite3.)

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]

Upvotes: 1

rd_nielsen
rd_nielsen

Reputation: 2459

SQLite doesn't support the information_schema, so you need to do something like this:

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]

Upvotes: 7

Related Questions