How to Alter a SQLite Table using Python ?
Last Updated :
03 Jun, 2021
In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module.
We can do this by using ALTER statement. It allows to:
- Add one or more column to the table
Change the name of the table.
Adding a column to a table
The syntax of ALTER TABLE to add a new column in an existing table in SQLite is given below:
ALTER TABLE table_name ADD COLUMN column_name colume_type
The column is added but will have all the values to be NULL.
To create a table:
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "DROP TABLE IF EXISTS GEEK" )
table =
cursor_obj.execute(table)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
connection_obj.execute(
)
data = cursor_obj.execute( )
print ( 'GEEK Table:' )
for row in data:
print (row)
connection_obj.commit()
connection_obj.close()
|
Output:
Now we add a new column “UserName”:
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
new_column = "ALTER TABLE GEEK ADD COLUMN UserName CHAR(25)"
cursor_obj.execute(new_column)
data = cursor_obj.execute( "SELECT * FROM GEEK" )
print ( 'GEEK Table:' )
for row in data:
print (row)
connection_obj.commit()
connection_obj.close()
|
Output:
Changing the name of the table
The syntax of ALTER TABLE to change the name of the table in SQLite is given below:
ALTER TABLE table_name RENAME TO newTableName;
We will use the same GEEK table that we created above:
Python3
import sqlite3
connection_obj = sqlite3.connect( 'geek.db' )
cursor_obj = connection_obj.cursor()
cursor_obj.execute( "SELECT * FROM sqlite_master" )
table = cursor_obj.fetchall()
print ( "Before changing the name of Table" )
print ( "The name of the table:" , table[ 0 ][ 2 ])
renameTable = "ALTER TABLE GEEK RENAME TO GFG"
cursor_obj.execute(renameTable)
cursor_obj.execute( "SELECT * FROM sqlite_master" )
table = cursor_obj.fetchall()
print ( "After changing the name of Table" )
print ( "The name of the table:" , table[ 0 ][ 2 ])
connection_obj.commit()
connection_obj.close()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...