How to Execute SQL queries from CGI scripts
Last Updated :
04 Jan, 2024
In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step involves creating a database, and it's worth noting that prebuilt databases can also be utilized for this purpose in Python.
What are SQL Queries?
SQL (Structured Query Language) is a programming language designed for managing and manipulating relational database systems. It provides a standardized way to interact with databases, allowing users to perform various operations such as querying data, updating records, inserting new data, and deleting information (CRUD Operation). SQL is widely used in the field of database management and is supported by most relational database management systems (RDBMS).
Execute SQL Queries From CGI Scripts
Below is a step-by-step guide to understanding how to execute SQL queries from CGI scripts in Python. Let's begin.
Required Installation
Here, we will install the following things to start with generating webpages using CGI scripts:
- Install Python
- Install Python CGI
- SQLite
Create Folder
In this article, we will explore the process of executing SQL queries from CGI (Common Gateway Interface) scripts. To begin, let's create a directory named "database" to house our CGI script. Within this folder, we'll generate a Python file, 'python.py', wherein our CGI script will be written. Additionally, we'll save our database within the same directory. The following provides a step-by-step guide to learning how to execute SQL queries from CGI scripts.

Write Python CGI Script to Execute SQL Queries
In this example the Python CGI script establishes a connection to an SQLite database and defines a function (`execute_query`) for executing SQL queries and retrieving results. It creates a table named "users" and inserts two sample records into the database.
Now, The script then retrieves form data using the `cgi` module, particularly an SQL query provided in the form. The HTML and CSS markup define a simple web form for entering SQL queries and displaying the results.
Upon form submission, the script executes the SQL query, handles any errors, and dynamically generates an HTML response, showcasing the query results or error messages. Finally, the script closes the database connection.
This code serves as a basic example of a CGI script for interacting with an SQLite database through a web interface.
Python3
#!C:\Program Files\Python311\python.exe
print("Content-type: text/html\n\n")
import cgi
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Function to execute SQL query and retrieve results
def execute_query(query, params=None):
try:
if query:
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
result = cursor.fetchall()
return result
else:
return "No query provided."
except Exception as e:
return f"Error executing query: {str(e)}"
# Create a table and insert two users into the database
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL
)
'''
insert_users_query = '''
INSERT INTO users (username, email) VALUES
('user1', '[email protected]'),
('user2', '[email protected]')
'''
# Execute the table creation and user insertion queries
execute_query(create_table_query)
execute_query(insert_users_query)
# Get form data
form = cgi.FieldStorage()
# Retrieve SQL query from the form
sql_query = form.getvalue('sql_query')
# HTML and CSS for the form and result display
html = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CGI Database Query</title>
<style>
body {{
font-family: 'Arial', sans-serif;
background-color: #f4f4f4;
margin: 20px;
}}
h1 {{
color: #333;
text-align: center;
}}
form {{
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 20px auto;
}}
label {{
display: block;
margin-bottom: 8px;
}}
textarea {{
width: 100%;
padding: 8px;
margin-bottom: 16px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}}
input[type="submit"] {{
background-color: #4caf50;
color: #fff;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}}
input[type="submit"]:hover {{
background-color: #45a049;
}}
h2 {{
color: #333;
margin-top: 20px;
}}
pre {{
white-space: pre-wrap;
background-color: #f9f9f9;
padding: 15px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}}
p.error {{
color: #ff0000;
font-weight: bold;
}}
</style>
</head>
<body>
<h1>CGI Database Query</h1>
<form method="post" action="/database/python.py"> <!-- Corrected form action -->
<label for="sql_query">Enter SQL Query:</label>
<textarea name="sql_query" rows="4" cols="10" required>{sql_query}</textarea><br>
<input type="submit" value="Execute Query">
</form>
<h2>Query Results:</h2>
"""
# Execute the SQL query and handle errors
try:
result = execute_query(sql_query)
html += f"<pre>{result}</pre>"
except Exception as e:
html += f"<p class='error'>Error: {str(e)}</p>"
html += """
</body>
</html>
"""
# Display the HTML
print(html)
# Close the database connection
conn.close()
Output

Configuration and Start the Xampp Server
You can refer Create a CGI Script for complete configuration and how we can start the server to run out CGI Script.
Step 5: Run the Script
In this step, we will run the CGI Script by using the following command in your web browser
http://127.0.0.1/database/python.py
Video Demonstration
Conclusion
In conclusion, the process of executing SQL queries from CGI scripts provides a dynamic and interactive means to interact with databases through web interfaces. This article demonstrated a step-by-step guide, illustrating how to create a CGI script in Python to handle SQL queries. By establishing a connection to an SQLite database, defining a function for query execution, and incorporating HTML/CSS for a user-friendly form, users can seamlessly input SQL queries and receive real-time results or error feedback
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read