mirror of
https://github.com/rasbt/python_reference.git
synced 2024-11-27 22:11:13 +00:00
29 lines
1.1 KiB
Python
29 lines
1.1 KiB
Python
# Sebastian Raschka, 2014
|
|
# Adding a new column to an existing SQLite database
|
|
|
|
import sqlite3
|
|
|
|
sqlite_file = 'my_first_db.sqlite' # name of the sqlite database file
|
|
table_name = 'my_table_2' # name of the table to be created
|
|
id_column = 'my_1st_column' # name of the PRIMARY KEY column
|
|
new_column1 = 'my_2nd_column' # name of the new column
|
|
new_column2 = 'my_3rd_column' # name of the new column
|
|
column_type = 'TEXT' # E.g., INTEGER, TEXT, NULL, REAL, BLOB
|
|
default_val = 'Hello World' # a default value for the new column rows
|
|
|
|
# Connecting to the database file
|
|
conn = sqlite3.connect(sqlite_file)
|
|
c = conn.cursor()
|
|
|
|
# A) Adding a new column without a row value
|
|
c.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}"\
|
|
.format(tn=table_name, cn=new_column1, ct=column_type))
|
|
|
|
# B) Adding a new column with a default row value
|
|
c.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct} DEFAULT '{df}'"\
|
|
.format(tn=table_name, cn=new_column2, ct=column_type, df=default_val))
|
|
|
|
# Committing changes and closing the connection to the database file
|
|
conn.commit()
|
|
conn.close()
|