-1

I have been using sqlite3 with python for creating databases. Till Now I have been successful, But Unfortunately I have No way Out Of This. I have A Table With 63 columns but I Want To Select Only 62 Out Of Them, I am Sure That I can write The Names of The Columns In The Select Statement. But Writing 62 Of Them seems like a non-logical(for a programmer like me) idea for me. I am using Python-sqlite3 databases. Is There A Way Out Of This

I'm Sorry If I am Grammarly Mistaken.

Thanks in advance

1 Answers1

0

With Sqlite, you can:

  1. do a PRAGMA table_info(tablename); query to get a result set that describes that table's columns
  2. pluck the column names out of that result set and remove the one you don't want
  3. compose a column list for the select statement using e.g. ', '.join(column_names) (though you might want to consider a higher-level SQL statement builder instead of playing with strings).

Example

A simple example using a simple table and an in-memory SQLite database:

import sqlite3

con = sqlite3.connect(":memory:")
con.executescript("CREATE TABLE kittens (id INTEGER, name TEXT, color TEXT, furriness INTEGER, age INTEGER)")

columns = [row[1] for row in con.execute("PRAGMA table_info(kittens)")]
print(columns)
selected_columns = [column for column in columns if column != 'age']
print(selected_columns)
query = f"SELECT {', '.join(selected_columns)} FROM kittens"
print(query)

This prints out

['id', 'name', 'color', 'furriness', 'age']
['id', 'name', 'color', 'furriness']
SELECT id, name, color, furriness FROM kittens
AKX
  • 152,115
  • 15
  • 115
  • 172