Alter A SQLite Table Using Python
Example 1 – Changing the name of the SQLite table using Python:
# ——Example Python Program to alter an SQLite Table——
# import the sqlite3 module
# Create a connection object
renameTable = «ALTER TABLE stud RENAME TO student»
# Query the SQLite master table
tableQuery = «select * from sqlite_master»
# Print the updated listed of tables after renaming the stud table
print(«Database Object Type: %s»%(table[0]))
print(«Name of the database object: %s»%(table[1]))
print(«Name of the table: %s»%(table[2]))
print(«SQL Statement: %s»%(table[4]))
# close the database connection
Output:
Database Object Type: table
Name of the database object: teacher
Name of the table: teacher
SQL Statement: CREATE TABLE teacher(id int,firstname varchar(32),lastname varchar(32))
Database Object Type: table
Name of the database object: student
Name of the table: student
SQL Statement: CREATE TABLE «student»(id int,firstname varchar(32),lastname varchar(32))
Example 2 – Adding one or more new columns to an SQLite table using Python:
# ——Example Python Program to add new columns to an existing SQLite Table——
# import the module sqlite3
# Make a connection to the SQLite DB
# Obtain a Cursor object to execute SQL statements
# Add a new column to student table
addColumn = «ALTER TABLE student ADD COLUMN Address varchar(32)»
# Add a new column to teacher table
addColumn = «ALTER TABLE teacher ADD COLUMN Address varchar(32)»
# Retrieve the SQL statment for the tables and check the schema
masterQuery = «select * from sqlite_master»
print(«Database Object Type: %s»%(table[0]))
print(«Database Object Name: %s»%(table[1]))
print(«**SQL Statement**: %s»%(table[4]))
# close the database connection
Output:
Database Object Type: table
Database Object Name: teacher
**SQL Statement**: CREATE TABLE teacher(id int,firstname varchar(32),lastname varchar(32), Address varchar(32))
Database Object Type: table
Database Object Name: student
**SQL Statement**: CREATE TABLE «student»(id int,firstname varchar(32),lastname varchar(32), Address varchar(32))