본문으로 바로가기
 

SQLite - SELECT Query - Tutorialspoint

SQLite - SELECT Query SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in the form of a result table. These result tables are also called result sets. Syntax Following is the basic syntax of SQLite SELECT st

www.tutorialspoint.com

테이블 리스트 보기

SQLite CLI 에서 테이블 리스트를 보는 명령어는 .table

(py36) PS C:\Users\Desktop\example\sqlite3_> sqlite3
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open blog.db
sqlite> .table
color

 

파이썬의 SQL 문법으로는 SELECT * from sqlite_master WHERE type='table'

다음과 같은 결과를 얻을 수 있습니다.

import sqlite3

conn = sqlite3.connect('blog.db')
cur = conn.cursor()

sql = '''SELECT * from sqlite_master WHERE type="table"'''
cur.execute(sql)

rows = cur.fetchall()
for row in rows:
    print(row)
('table', 'color', 'color', 2, 'CREATE TABLE color (id integer, name text, rgb text)')
('table', 'no_colors', 'no_colors', 3, 'CREATE TABLE no_colors (id integer, name text, rgb text)')

 

테이블 생성 예외처리

이미 존재하는 테이블을 생성하려고 하면 에러가 발생합니다.

sqlite3.OperationalError: table color already exists

 

해당 테이블이 존재하는지 확인하고 없을 경우에만 테이블을 생성합니다.

row[1] 은 존재하는 테이블 이름입니다.

import sqlite3

conn = sqlite3.connect('blog.db')
cur = conn.cursor()

table_name = 'color'

sql = f'SELECT * from sqlite_master WHERE type="table" AND name="{table_name}"'
cur.execute(sql)
rows = cur.fetchall()
if rows:
    print('exist, no create table')
else:
    sql = 'CREATE TABLE {} (id integer, name text, rgb text)'.format(table_name)
    cur.execute(sql)
    conn.commit()
    
conn.close()