Python SQLite
Python SQLite
Programming in python 1
INSERT INTO movie VALUES
('Monty Python and the Holy Grail', 1975, 8.2),
('And Now for Something Completely Different', 1971, 7.5)
""")
The INSERT statement implicitly opens a transaction, which needs to be committed before
changes are saved in the database (see Transaction control for details). Call con.commit() on
the connection object to commit the transaction:
con.commit()
We can verify that the data was inserted correctly by executing a SELECT query. Use the now-
familiar cur.execute(...) to assign the result to res, and call res.fetchall() to return all resulting
rows:
>>>res = cur.execute("SELECT score FROM movie")
>>>res.fetchall()
[(8.2,), (7.5,)]
The result is a list of two tuples, one per row, each containing that row’s score value.Now, insert
three more rows by calling cur.executemany(...):
data = [
("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
("Monty Python's The Meaning of Life", 1983, 7.5),
("Monty Python's Life of Brian", 1979, 8.0),
]
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
con.commit()
Finally, verify that the database has been written to disk by calling con.close() to close the
existing connection, opening a new one, creating a new cursor, then querying the database:
con.close()
Create Table
To create a table in SQLite, you can use the CREATE TABLE statement. Here's a basic
example:
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
Programming in python 2
age INTEGER,
department TEXT
);
Let me break down this example:
Programming in python 3
• (column1, column2, column3, ...): Optional - specify the columns for which you're
providing values. If you omit this part, you should provide values for all columns in the
order they appear in the table.
• VALUES (value1, value2, value3, ...): Specify the values you want to insert into the
corresponding columns. Make sure the order of values matches the order of columns.
Here's an example using a hypothetical table called employees with columns id, name, and
salary:
INSERT INTO employees (id, name, salary) VALUES (1, 'John Doe', 50000);
If you want to insert values for all columns and in the same order as they are defined in the
table, you can skip specifying the column names:
INSERT INTO employees VALUES (1, 'John Doe', 50000);
Python code for insert table
import sqlite3
conn = sqlite3.connect('employee.db') # Connect to the SQLite database
cursor = conn.cursor() # Create a cursor object to interact with the database
create_table_query = '''CREATE TABLE IF NOT EXISTS employee (id INTEGER PRIMARY
KEY, name TEXT, department TEXT);'''
# Define the SQL query to create a table if it doesn't exist
cursor.execute(create_table_query) # Execute the create table query
insert_data_query = '''INSERT INTO employee(id, name,department) VALUES (?, ?,?);'''
# Insert data into the table
data_to_insert = (?, 42) # Data to be inserted
data_to_insert1 = (?,”Mahesh”)
data_to_insert2= (?, “Manager”)
cursor.execute(insert_data_query, data_to_insert, data_to_insert1, data_to_insert2) # Execute
the insert data query with the provided data
conn.commit() # Commit the changes to the database
cursor.close() # Close the cursor and connection
conn.close()
Select
The SELECT command in SQLite is used to query data from one or more tables in a database.
Here's a basic syntax for the SELECT command:
Programming in python 4
SELECT column1, column2, ...
FROM table_name
WHERE condition;
• column1, column2, ...: The columns you want to retrieve in the result set.
• table_name: The name of the table from which you want to retrieve data.
• WHERE condition: Optional. It specifies a condition to filter the rows returned.
Here are a few examples:
• Retrieve all columns from a table:
SELECT *FROM student;
• Retrieve data with a condition:
SELECT * FROM student WHERE id = 456;
• Use logical operators in the WHERE clause:
SELECT * FROM student WHERE id = 456 AND name=”suresh”;
Python code for select command
import sqlite3
conn = sqlite3.connect('student.db') # Connect to the SQLite database
cursor = conn.cursor() # Create a cursor object to interact with the database
cursor.execute("SELECT * FROM student;") # Execute a SELECT command
results = cursor.fetchall() # Fetch the results
for row in results:
print(row) # Iterate through the results and print them
cursor.close() # Close the cursor and connection
conn.close()
Update.
The SQLite UPDATE statement is used to modify the existing records in a table. The basic
syntax for the UPDATE statement is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• UPDATE: Keyword indicating the beginning of the UPDATE statement.
• table_name: The name of the table from which you want to update records.
• SET: Keyword indicating the columns to be modified and their new values.
• column1 = value1, column2 = value2, ...: The columns to be updated along with their
new values.
Programming in python 5
• WHERE: Optional keyword to specify a condition for which records to update. If
omitted, all records in the table will be updated.
• condition: The condition that must be met for a record to be updated. If omitted (or if
you omit the entire WHERE clause), all records will be updated.
Here's a simple example:
UPDATE employees SET salary = 50000, department = 'IT' WHERE employee_id = 123;
This example updates the salary and department columns for the employee with an
employee_id of 123 in the "employees" table.
Python code for update command
import sqlite3
conn = sqlite3.connect('employee.db') # Connect to the SQLite database
cursor = conn.cursor()
new_value = 'suresh'
old_value = 'harish'
update_query = f"UPDATE employee SET name = ? WHERE name= ?" # Update command
cursor.execute(update_query, (new_value, old_value)) # Execute the update query
conn.commit() # Commit the changes and close the connection
conn.close()
Delete
In SQLite, you can use the DELETE command to remove rows from a table based on a
specified condition. The basic syntax for the DELETE command is as follows:
DELETE FROM table_name
WHERE condition;
• table_name is the name of the table from which you want to delete data.
• condition is an optional part that specifies the criteria for deleting rows. If you omit the
WHERE clause, all rows in the table will be deleted.
Here are a few examples:
• Delete all rows from a table:
DELETE FROM employee;
Programming in python 6
Python code for delete command
import sqlite3
conn = sqlite3.connect('employee.db') # Connect to the SQLite database
cursor = conn.cursor() # Create a cursor object to execute SQL commands
delete_query = "DELETE FROM employee WHERE id= ?"
value_to_delete = (67,)
cursor.execute(delete_query, value_to_delete) # Execute the DELETE command
conn.commit() # Commit the changes to the database
cursor.close()
conn.close()
Drop
In SQLite, the DROP command is used to delete database objects such as tables, indexes, or
views. The basic syntax for the DROP command is as follows:
DROP [object_type] [IF EXISTS] object_name;
• object_type: Specifies the type of object to drop (e.g., TABLE, INDEX, VIEW).
• IF EXISTS: Optional clause that prevents an error from occurring if the object doesn't
exist.
• object_name: The name of the object you want to drop.
Drop a Table:
DROP TABLE IF EXISTS employee;
Programming in python 7