0% found this document useful (0 votes)
3 views7 pages

Python SQLite

The document provides an overview of using the SQLite3 module in Python for database management, including creating, inserting, selecting, updating, deleting, and dropping tables. It explains the basic syntax for SQL commands and provides Python code examples for each operation. The document emphasizes the lightweight nature of SQLite and its applicability for prototyping applications before transitioning to larger databases.

Uploaded by

shrilathapcmb21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Python SQLite

The document provides an overview of using the SQLite3 module in Python for database management, including creating, inserting, selecting, updating, deleting, and dropping tables. It explains the basic syntax for SQL commands and provides Python code examples for each operation. The document emphasizes the lightweight nature of SQLite and its applicability for prototyping applications before transitioning to larger databases.

Uploaded by

shrilathapcmb21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python SQLite

The SQLite3 module


SQLite is a C library that provides a lightweight disk-based database that doesn’t require a
separate server process and allows accessing the database using a nonstandard variant of the
SQL query language. Some applications can use SQLite for internal data storage. It’s also
possible to prototype an application using SQLite and then port the code to a larger database
such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant
with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
SQLite Methods
You will create a database of using basic sqlite3 functionality. It assumes a fundamental
understanding of database concepts, including cursors and transactions.
First, we need to create a new database and open a database connection to allow sqlite3 to work
with it. Call sqlite3.connect() to create a connection to the database tutorial.db in the current
working directory, implicitly creating it if it does not exist:
import sqlite3
con = sqlite3.connect("tutorial.db")
The returned Connection object con represents the connection to the on-disk database.
In order to execute SQL statements and fetch results from SQL queries, we will need to use a
database cursor. Call con.cursor() to create the Cursor:
cur = con.cursor()
Now that we’ve got a database connection and a cursor, we can create a database table movie
with columns for title, release year, and review score. For simplicity, we can just use column
names in the table declaration – thanks to the flexible typing feature of SQLite, specifying the
data types is optional. Execute the CREATE TABLE statement by calling cur.execute(...):
cur.execute("CREATE TABLE movie(title, year, score)")
We can verify that the new table has been created by querying the sqlite_master table built-in
to SQLite, which should now contain an entry for the movie table definition (see The Schema
Table for details). Execute that query by calling cur.execute(...), assign the result to res, and
call res.fetchone() to fetch the resulting row:
>>>res = cur.execute("SELECT name FROM sqlite_master")
>>>res.fetchone()
('movie',)
We can see that the table has been created, as the query returns a tuple containing the table’s
name. If we query sqlite_master for a non-existent table spam, res.fetchone() will return None:
cur.execute("""

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:

• CREATE TABLE: This is the command to create a new table.


• IF NOT EXISTS: This part is optional and ensures that the table is only created if it
doesn't already exist.
• employees: This is the name of the table.
• (id INTEGER PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT NOT
NULL, age INTEGER, department TEXT): These are the columns of the table, along
with their data types and constraints.
In this example:
• id is an integer column and is also the primary key.
• first_name and last_name are text columns that cannot be NULL.
• age is an optional integer column.
• department is a text column that can be NULL.
Python code for create table
import sqlite3
conn = sqlite3.connect('student.db') # Connect to SQLite database
cursor = conn.cursor() # Create a cursor object to interact with the database
create_table_query = '''CREATE TABLE IF NOT EXISTS student ( id INTEGER PRIMARY
KEY , name TEXT, age INTEGER);''' # Define your table schema and execute the CREATE
TABLE statement
cursor.execute(create_table_query)
conn.commit() # Commit the changes and close the connection
conn.close()
Operations on Tables
Insert
To insert data into an SQLite table, you can use the INSERT INTO statement. Here's a basic
syntax for inserting data into a table:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• table_name: The name of the table into which you want to insert data.

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;

• Delete rows based on a condition:


DELETE FROM employee WHERE id= 46;
• Delete rows using multiple conditions:
DELETE FROM employee WHERE name = ‘suresh’ AND salary > 20000;

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;

Python code for drop command


import sqlite3
conn = sqlite3.connect('employee.db')
cursor = conn.cursor()
table_name_to_drop = 'employee'
drop_query = f'DROP TABLE IF EXISTS {table_name_to_drop};' # SQL query to drop a table
cursor.execute(drop_query) # Execute the query
conn.commit()
cursor.close()
conn.close()

Programming in python 7

You might also like