0% found this document useful (0 votes)
13 views19 pages

SQLite Database Programming Basics

Module IV covers Database Programming and CGI Programming in Python. It explains how to connect to an SQLite database, execute SQL statements, and manage data (insert, update, delete) using Python's sqlite3 library. Additionally, it introduces CGI programming for generating dynamic web content, including handling forms and various input types such as text fields, radio buttons, checkboxes, and file uploads.

Uploaded by

babysmitha14
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)
13 views19 pages

SQLite Database Programming Basics

Module IV covers Database Programming and CGI Programming in Python. It explains how to connect to an SQLite database, execute SQL statements, and manage data (insert, update, delete) using Python's sqlite3 library. Additionally, it introduces CGI programming for generating dynamic web content, including handling forms and various input types such as text fields, radio buttons, checkboxes, and file uploads.

Uploaded by

babysmitha14
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

Module IV

Database Programming

1. Connecting to a Database
To work with SQLite in Python, you first need to connect to a database file. If the
file does not exist, SQLite will create it for you.

 Connecting: The connect method establishes a connection to the


specified SQLite database file ([Link] in this case). If the file does
not exist, SQLite will create it.
 Connection Object: The return value conn is an instance of the
Connection class, which allows you to interact with the database using
cursors (Cursor objects).
 Database Operations: Once connected, you can execute SQL
statements, create tables, insert data, and retrieve data using the
Connection object and its associated Cursor objects.
 Closing the Connection: It’s important to close the connection
([Link]()) when you’re finished working with the database to
ensure that any pending transactions are committed or rolled back
properly, and to release any resources associated with the connection.
2. Executing SQL Statements
Once connected, you can execute SQL statements using the execute() method
of the cursor object.

The execute() method is used to execute SQL queries or commands against an


SQLite database. This method belongs to the Cursor object, which is created
from a Connection object (established using [Link]()).

3. Fetching Data
You can fetch data from the database using methods like fetchone(), fetchall(),
or by iterating over the cursor directly.
4. Updating Data
In the users table with columns id, name, and age. We'll update the age of a
user with a specific id.

import sqlite3

# Connect to SQLite database (create if not exists)


conn = [Link]('[Link]')
cursor = [Link]()

# Execute an UPDATE query


[Link](“’UPDATE users SET age = 25 WHERE id = 1“’)

# Commit the changes


[Link]()

# Print a message indicating the update was successful


print(‘Age updated successfully ‘)

# Close the cursor and connection


[Link]()
[Link]()
 [Link]() commits the changes made by the UPDATE statement to the
database. This step is necessary to persist the changes permanently.

5. Deleting Data
We'll delete a user based on their id.

import sqlite3

# Connect to SQLite database (create if not exists)


conn = [Link]('[Link]')
cursor = [Link]()

# Execute a DELETE query


[Link](“’DELETE FROM users WHERE id=1“’)

# Commit the deletion


[Link]()

# Print a message indicating the deletion was successful


print("Deleted successfully")

# Close the cursor and connection


[Link]()
[Link]()
4. Closing the Connection

Example: Complete Code

import sqlite3

# Connect to SQLite database (creates a new database if not exists)


conn = [Link]('[Link]')
cursor = [Link]()

# Create table
[Link]('''CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER )''')

# Insert data
[Link]('''INSERT INTO users VALUES (1,’Milan’,21)
[Link]('''INSERT INTO users VALUES (2,’Ammu’,22)
[Link]('''INSERT INTO users VALUES (3,’Mubeen’,25)
z
# Commit changes
[Link]()

# Fetch and print data


[Link]('SELECT * FROM users')
rows = [Link]()

for row in rows:


print(row)

Print (“Result displayed Succesffully”)

[Link](“’UPDATE users SET age = 25 WHERE id = 1“’)


[Link]()
print(‘Age updated successfully ‘)

[Link](“’DELETE FROM users WHERE id=1“’)


[Link]()
print("Deleted successfully")

# Close cursor and connection


[Link]()
[Link]()
Iterator
An iterator is an object that allows you to iterate over elements in a sequence,
container, or collection one by one, without needing to know the underlying
data structure or implementation details. Iterators are essential for loops, as
they provide a consistent way to access elements from various data types.

Whenever you use a for loop in Python, it implicitly uses an iterator to loop
through the elements of an iterable.

The primary methods associated with iterators are:

1. iter() : This function is used to create an iterator from an iterable object.


An iterable can be any data structure that supports iteration, such as lists,
tuples, dictionaries, strings, sets, etc.

2. next() : This method is used to retrieve the next element from the iterator.
When there are no more elements to be fetched, it raises the
StopIteration exception.

Data Types supports Iterators

 List

my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)

print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
# ... and so on
 Strings

my_string = "Hello"
my_iterator = iter(my_string)

print(next(my_iterator)) # Output: 'H'


print(next(my_iterator)) # Output: 'e'
# ... and so, on

 Dictionaries

my_dict = {'a': 1, 'b': 2, 'c': 3}


my_iterator = iter(my_dict)

print(next(my_iterator)) # Output: 'a' (dictionary keys are iterated)


print(next(my_iterator)) # Output: 'b'
# ... and so on

 Sets

my_set = {1, 2, 3, 4, 5}
my_iterator = iter(my_set)

print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
# ... and so on
CGI Programming

 What is CGI?

CGI (Common Gateway Interface) programming is a technique used to generate


dynamic web content by executing scripts on a web server. It allows the server
to interact with external programs or scripts and generate dynamic HTML
pages or other types of content in response to user requests.

When a user sends a request to a web server, the server identifies the requested
resource and checks if it requires any dynamic content. If dynamic content is
needed, the server invokes the CGI program associated with that resource.
The CGI program processes the request, performs any necessary computations
or data manipulations, and generates a response that is sent back to the user's
browser.

CGI programming in Python involves writing Python scripts that can be executed
by a web server to generate dynamic content. These scripts can receive input
from the user through HTML forms, process the input, and generate a
response that is sent back to the user.

CGI programming in Python typically involves handling HTTP headers, accessing


environment variables, processing form data, handling cookies, and generating
HTML output. Python provides libraries and modules, such as cgi and http
modules, that simplify the process of writing CGI scripts.

Example:

Explanation

1. print() Function:

In Python, print() is a built-in function used to display output to the


console or, in the case of CGI scripts, to send content to the web server which
in turn sends it to the web browser.

2. "Content-type:text/html\r\n\r\n":

This string is a part of the HTTP header. In the context of CGI scripts and
web development:

 Content-type specifies the type of content being sent.


text/html indicates that the content being sent is HTML
(Hypertext Markup Language).

 \r\n is a carriage return (\r) followed by a newline (\n), which


are HTTP protocol standard line endings.
 Forms

#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>CGI Form Example</h1>")
print("<form method='post'
action='process_form.py'>")
print("Name: <input type='text'
name='name'><br>")
print("<input type='submit'
value='Submit'>")
print("</form>")
print("</body></html>")

Output:

Explanation

print("<form method='post' action='process_form.py'>")

This line starts an HTML <form> element. The method attribute is set to 'post',
which means that when the user submits the form, the data will be sent to the
server using the HTTP POST method.

The action attribute is set to 'process_form.py’, which indicates that the form
data should be sent to the process_form.py script for processing.
print("Name: <input type='text' name='name'><br>")

This line generates an HTML text input field labeled "Name." The name attribute
is set to 'name' , which will be used as the key when the form data is sent to the
server.

print("<input type='submit' value='Submit'>")

This line generates an HTML submit button that the user can click to submit the
form.

type='submit' : This specifies that the <input> element is a submit button. When
the user clicks this button, it will trigger the form submission.

value='Submit' : This sets the text that will be displayed on the submit button.
In this case, the text "Submit" will be shown on the button.

rest of the tags are closing tags.

 Radio Button

Radio buttons are a type of form input element in HTML that allow users to
select one option from a set of options. Radio buttons are often used when
there is a list of related choices, and the user needs to select a single option
from that list.

Example

#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Gender Selection</h1>")
# Radio buttons for gender
print("<h3>Select your gender:</h3>")
print("<input type='radio' name='gender' value='male'> Male<br>")
print("<input type='radio' name='gender' value='female'>
Female<br>")
print("<input type='radio' name='gender' value='other'> Other<br>")
print("</body></html>")
Output

Explanation

print("<input type='radio' name='gender' value='male'> Male<br>")


print("<input type='radio' name='gender' value='female'> Female<br>")
print("<input type='radio' name='gender' value='other'> Other<br>")

These lines generate the radio buttons for gender selection. Each radio button
is created using the <input> element with the type='radio' attribute. The name
attribute groups the radio buttons together, and the value attribute specifies
the value associated with each radio button. When the user selects one radio
button, the corresponding value will be sent to the server when the form is
submitted.

 Drop down Box


A Drop-down box, also known as a select element with multiple options, allows
users to choose one or more options from a list.

Example

#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Country Selection</h1>")
# Dropdown box for country selection
print("<h3>Select your country:</h3>")
print("<select name='country'>")
print("<option value='usa'>United States</option>")
print("<option value='canada'>Canada</option>")
print("<option value='uk'>United Kingdom</option>")
print("<option value='australia'>Australia</option>")
print("</select>")
print("</body></html>")

Output

Explanation

print("<select name='country'>")
print("<option value='usa'>United States</option>")
print("<option value='canada'>Canada</option>")
print("<option value='uk'>United Kingdom</option>")
print("<option value='australia'>Australia</option>")
print("</select>")

These lines create the dropdown box (select element) for country selection.
Here's what each part does:
The <select> element starts the dropdown box. The name attribute specifies the
name of the form field, which will be used to identify the selected option when
the form is submitted.
Each country option is defined using the <option> element. The value attribute
of each option specifies the value associated with that option. When the user
selects an option, the corresponding value will be sent to the server when the
form is submitted. The text inside the <option> tags is what the user sees in the
dropdown.

The </select> tag closes the dropdown box.

 Check Box

Checkboxes are used to allow users to select one or more options from a list.

Example

#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")

print("<html><body>")
print("<h1>Language Selection</h1>")
# Checkboxes for language selection
print("<h3>Select your languages:</h3>")
print("<form method='post' action='process_form.py'>")
print("<input type='checkbox' name='language' value='english'> English<br>")
print("<input type='checkbox' name='language' value='french'> French<br>")
print("<input type='checkbox' name='language' value='spanish'> Spanish<br>")
print("<input type='checkbox' name='language' value='german'> German<br>")
print("<br>")

# Submit button
print("<input type='submit' value='Submit'>")
print("</form>")
print("</body></html>")
Output

Explanation

print("<input type='checkbox' name='language' value='english'> English<br>")

This line generates an HTML checkbox input element. Here's what each attribute
does:
type='checkbox' : Specifies that the input element is a checkbox.

name='language' : Sets the name attribute to "language." This groups the


checkboxes together under the same name, allowing multiple checkboxes to be
selected and sent as an array when the form is submitted.

value='english' : Sets the value that will be sent to the server when the checkbox
is selected. In this case, the value "english" is associated with the English
language.

The label text "English" is displayed next to the checkbox.

<br> : Adds a line break to move to the next line.

 Text Area
A text area is used to allow users to input multi-line text.
Example

#!/usr/bin/python3
print("Content-
type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Feedback Form</h1>")
# Text area for user feedback
print("<h3>Provide your
feedback:</h3>")
print("<textarea name='feedback'
rows='5' cols='40'></textarea>")
print("<br>")
print("</body></html>")

Output

Explanation

print("<textarea name='feedback' rows='5' cols='40'></textarea>")

In this script:

The textarea element is used to create a multi-line text input area.


The name attribute specifies the name of the form field, which will be used to
identify the text entered by the user when the form is submitted.
The rows attribute determines the number of visible rows in the text area.
The cols attribute determines the number of visible columns (characters) in the
text area.

 Uploading file

Uploading files via HTTP requests, including in Python CGI scripts, involves
creating an HTML form with an input element of type "file.”

Example

#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")

print("<html><body>")
print("<h1>File Upload Example</h1>")
print("<form method='post' enctype='multipart/form-
data' action='process_upload.py'>")

print("<input type='file' name='upload_file'><br>")


print("<input type='submit' value='Upload'>")
print("</form>")
print("</body></html>")

Output:
Explanation

1. <form method='post' enctype='multipart/form-data'


action='process_upload.py'> :

<form> is the HTML element used to create a form.


method='post' specifies that the form data should be sent using the HTTP
POST method.

enctype='multipart/form-data' is crucial for file uploads. It indicates that the


form data includes binary files and needs special encoding for transmission.

action='process_upload.py' sets the URL where the form data will be sent for
processing. In this case, it's set to 'process_upload.py' , meaning the form data
will be handled by a script named process_upload.py .

2. <input type='file' name='upload_file'><br> :


<input> is an HTML element used for various types of user input.
type='file' specifies that this input element is used for file uploads.

name='upload_file' assigns a name to the input element. This name will be


used to identify the uploaded file when processing the form data.

The <br> tag adds a line break, moving the next HTML element to a new line.

3. <input type='submit' value='Upload'>:


Another <input> element, this time with type='submit’. It's used to create a
submit button.
value='Upload' sets the text that appears on the submit button.

4. </form>:
Closes the <form> element, indicating the end of the form definition

You might also like