Python Module IV
Python Module IV
Python : Module IV
Database Programming
Connection
The mysql.connector provides the connect() method used to create a connection between the MySQL database and
the Python application.
syntax
Username – It represents the name of the user that we use to work with the MySQL server. By default, the username
for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL database. We don’t need to pass a
password if we are using the root.
Database – It specifies the database name which we want to connect. This argument is used when we have multiple
databases.
Example
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="Batman",
passwd="12345",
Create
To create a new database using Python's MySQL Connector, follow these steps:
1. Import the necessary module: Begin by importing the mysql.connector module, which provides the functionality to
connect and interact with MySQL databases.
2. Establish a connection: Use the mysql.connector.connect() function to establish a connection to the MySQL server.
Provide the appropriate host , user , and passwd (password) values for the connection.
3. Create a cursor: After connecting, create a cursor object using the db.cursor() method. The cursor allows you to
execute SQL queries on the database.
Python : Module IV 1
4. Execute the SQL query: Use the cursor's execute() method to run the SQL query that creates the new database.
The query should be in the format: CREATE DATABASE <database_name>; , where <database_name> is the desired name for
the new database.
5. Commit the changes: For the database creation to take effect, use the db.commit() method to commit the changes.
This step is essential to save the database creation operation.
6. Close the cursor and connection: Close the cursor and the database connection to free up resources and manage
the connection lifecycle properly. Use the cursorObject.close() and db.close() methods, respectively.
syntax:
import mysql.connector
# Create a connection to the database
#auth
db = mysql.connector.connect(
host="<hostname>",
user="<username>",
passwd="<password>",
)
Example
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="Batman",
passwd="12345"
)
cursorObject = db.cursor()
Insert
To insert a data :
Python : Module IV 2
1. Establish a connection to the database:
The first step is to connect to the MySQL database using the mysql.connector.connect() method. You need to
provide the appropriate values for <hostname> , <username> , <password> , and <database_name> . This step allows the
script to connect to the desired database for further operations.
data_to_insert tuple is passed as the second argument to the execute() method, which replaces the %s
placeholders in the query with the actual data.
syntax:
import mysql.connector
data_to_insert = ("Value1", "Value2", "Value3") # Replace these values with your actual data
Python : Module IV 3
Example
import mysql.connector
db=mysql.connector.connect(host="localhost",
user="Aswin",
passwd="12345",
database="members")
mycursor = db.cursor()
table_name = 'student'
data =("joy","CSE",12,"AN",21)
mycursor.execute(insert_qry,data)
db.commit()
mycursor.close()
db.close()
update
The update is used to change the existing values in a database. By using update a specific value can be corrected or
updated. It only affects the data and not the structure of the table.
The basic advantage provided by this command is that it keeps the table accurate.
syntax
UPDATE tablename
SET ="new value"
WHERE ="old value";
Total Code:
import mysql.connector
#Query
Query =''' UPDATE <table_name>
Python : Module IV 4
SET "<new_value>"
WHERE "<old_value>" '''
cursorObject.execute(Query)
db.commit
db.close
Example
import mysql.connector
db=mysql.connector.connect(host="localhost",
user="Aswin",
passwd="12345",
database="members")
mycursor = db.cursor()
mycursor.execute(Qry)
db.commit()
mycursor.close()
db.close()
Delete
Delete is used to remove a certain row from the table
Syntax:
Total Code:
import mysql.connector
Python : Module IV 5
cursorObject = db.cursor()
#Query
Query =''' DELETE FROM "<table_name>"
WHERE "<Attribute_value>" '''
cursorObject.execute(Query)
db.commit
db.close()
Commit
db.commit() is used to commit the changes made to the database after executing data manipulation (INSERT,
UPDATE, DELETE) operations within a transaction. It is an essential step to make the changes permanent in the
database.
In Python's MySQL Connector, after executing data manipulation queries (e.g., INSERT, UPDATE, DELETE), you
need to call the commit() method on the database connection object to save the changes to the database.
import mysql.connector
In this example, the code establishes a connection to the MySQL database, creates a cursor object, and then executes
a data manipulation operation (INSERT) by calling cursor.execute(insert_query) . After executing the query, the changes
are not yet saved to the database. The db.commit() method is called immediately after the data manipulation operation
to commit the changes and make them permanent in the database.
Without the db.commit() call, the changes would not be saved, and any data manipulation operations within the
transaction would not be persisted in the database.
Python : Module IV 6
Rollback
" rollback " is an operation that undoes all the changes made within the current transaction, effectively reverting the
database to its state before the transaction began. This ensures that if any part of the transaction fails or encounters
an error, the database remains consistent and no partial or invalid data is left behind.
The rollback operation is essential for maintaining data integrity, as it allows you to undo the changes made during a
failed transaction and prevent any unintended side effects.
syntax
db.rollback()
Example
import mysql.connector
db=mysql.connector.connect(host="localhost",
user="Aswin",
passwd="12345",
database="members")
mycursor = db.cursor()
mycursor.execute("BEGIN")
mycursor.execute('''UPDATE student
SET Age =19
WHERE name = 'john'
''')
db.commit()
db.close()
Here,
1. Starting a transaction: The code executes the SQL statement mycursor.execute("BEGIN") . This line starts a
transaction. In MySQL, a transaction is a sequence of one or more SQL statements treated as a single unit of
work. By starting a transaction with BEGIN , any subsequent SQL statements executed using the cursor will be
part of this transaction until either a COMMIT or ROLLBACK statement is issued.
2. Executing an UPDATE statement: The script executes an SQL UPDATE statement using the cursor. The UPDATE
statement modifies records in the "student" table. In this specific case, it sets the "Age" column to 19 for the
student with the name "john." However, since the transaction hasn't been committed yet, this change is not yet
permanently saved to the database.
3. Performing a rollback: The next line of code, db.rollback() , is the critical part for a rollback. A rollback undoes
any changes made within the current transaction. In this case, since we started the transaction before the
UPDATE statement, the UPDATE operation on the "Age" column for the student named "john" will be undone. The
database will revert to its state before the transaction began, and "john" will retain their original age.
4. Committing the transaction (optional): After performing the rollback, the code has db.commit() in the script.
However, it's important to note that a rollback already undoes any changes, and a commit is used to
permanently save the changes made within the transaction. In this case, since the rollback was performed,
there are no valid changes to commit. So, this line is not necessary and can be removed from the code.
Python : Module IV 7
5. Closing the database connection: Finally, the script closes the database connection using db.close() to release
any resources associated with the connection.
Disconnection
Proper disconnection from the database is essential to release resources and manage the connection lifecycle
efficiently.When you are finished executing queries and performing operations on the database, you should close the
database connection and the cursor properly.
db.close()
Total Code
import mysql.connector
Exceptions
Exceptions are a mechanism to handle errors and exceptional situations that may occur during the execution of a
program. When an error occurs, Python raises an exception, which can be caught and handled using exception
handling techniques. Exception handling allows you to gracefully recover from errors and take appropriate actions to
maintain program flow and data integrity.
Exceptions can occur when there are errors in the database connection, SQL queries, or any other database-related
operations. Common exceptions related to database operations include:
1. mysql.connector.Error : This is a generic exception class provided by the MySQL Connector module that represents
errors related to MySQL databases. It can be caught to handle various database-related exceptions.
Python : Module IV 8
2. mysql.connector.InterfaceError : This exception is raised when there is a problem with the MySQL Connector
interface.
3. mysql.connector.DatabaseError : This exception is raised for errors related to the database, such as connection errors
or query execution errors.
4. mysql.connector.IntegrityError : This exception is raised when there is a constraint violation, like trying to insert a
5. mysql.connector.ProgrammingError : This exception is raised for errors in SQL syntax or incorrect usage of the MySQL
Connector API.
Example
import mysql.connector
try:
# Create a connection to the database
db = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="mydatabase"
)
except mysql.connector.Error as e:
# Handle specific MySQL Connector exceptions
print("MySQL Connector Error:", e)
except Exception as e:
# Handle other general exceptions
print("General Exception:", e)
finally:
# Close the cursor and the database connection
cursor.close()
db.close()
In this example, we use a try-except block to catch specific MySQL Connector exceptions using mysql.connector.Error ,
and a general Exception class to handle any other unanticipated exceptions. The finally block ensures that we
properly close the cursor and database connection, regardless of whether an exception occurred or not.
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.
1. iter() : This function is used to create an iterator from an iterable object. An iterable can be any data structure that
2. next() : This method is used to retrieve the next element from the iterator. When there are no more elements to be
Python : Module IV 9
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)
Dictionaries
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
https://youtu.be/GVONOAEID5E
What is CGI?
Python : Module IV 10
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.
#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>It works!</h1>")
print("</html></body>")
output
Python : Module IV 11
HTTP headers
In this case, the line print("Content-type:text/html\r\n\r\n") within your Python CGI script is setting an HTTP
header.This is a content type HTTP header.
The Content-type HTTP header informs the client (usually a web browser) about the type of content being sent in
the HTTP response. In your script, it specifies that the response content is in HTML format. This header is crucial
because it helps the client understand how to interpret and render the content it receives.
The double line break ( \r\n\r\n ) after the Content-type header indicates the end of the headers section and the
beginning of the actual content. This separation is necessary because HTTP responses consist of two parts:
headers and content. The headers provide metadata about the content, while the content itself follows the
headers.
Content Negotiation: Clients and servers can use headers to negotiate the best content format to use, such as
language preferences ( Accept-Language ) or content encoding ( Accept-Encoding ).
Caching and Freshness: Headers like Cache-Control and Expires allow servers to specify how long a resource
should be cached by the client's browser.
Authentication and Authorization: Headers like Authorization are used for security, allowing clients to provide
authentication credentials to access protected resources.
Redirects: Headers like Location are used to indicate to the client that the requested content is available at a
different URL.
Python : Module IV 12
Status Codes: HTTP headers also include the status code, which indicates the success or failure of the request.
For example, 200 OK indicates success, while 404 Not Found indicates that the requested resource was not found.
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
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.
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.
Python : Module IV 13
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
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>")
print("</body></html>")
output
Explanation
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
Python : Module IV 14
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.
#!/usr/bin/python3
print("Content-type:text/html\r\n\r\n")
print("<html><body>")
print("<h1>Country Selection</h1>")
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.
Python : Module IV 15
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>")
# Submit button
print("<input type='submit' value='Submit'>")
print("</form>")
print("</body></html>")
output
Explanation
This line generates an HTML checkbox input element. Here's what each attribute does:
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.
Text Area
Python : Module IV 16
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>")
print("</body></html>")
output
Explanation
In this script:
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.
Cookies
Cookies are small pieces of data that a web server can store on a user's device. They are often used to track user
information, preferences, and session data.
The http.cookies module is a part of the Python standard library that provides classes for working with cookies in
HTTP requests and responses
Example
Python : Module IV 17
#!/usr/bin/python3
# the above line is called shebang line that specifies the path to the Python interpreter that should be used to run the scri
import http.cookies
# Set a cookie
cookie = http.cookies.SimpleCookie()
cookie["username"] = "john"
output
The data username = john will be stored in the browser’s cache
Explanation
1. cookie = http.cookies.SimpleCookie() : This line creates an instance of the SimpleCookie class. This object is used to
work with cookies, allowing you to create, manage, and manipulate cookies in an HTTP response.
2. cookie["username"] = "john" : This line sets a cookie named "username" with the value "john." The square bracket
notation is used to assign a value to a cookie within the SimpleCookie object. This sets up the cookie to be included
in the HTTP response.
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("</body></html>")
output
Explanation
Python : Module IV 18
1. <form method='post' enctype='multipart/form-data' action='process_upload.py'> :
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 .
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.
Another <input> element, this time with type='submit' . It's used to create a submit button.
4. </form> :
Closes the <form> element, indicating the end of the form definition
Python : Module IV 19