[Go to site: main page, start]

100% found this document useful (1 vote)
101 views4 pages

Python SQL Database Connectivity Guide

This document discusses database connectivity in Python. It provides steps to connect Python to an SQL database using the mysql.connector package. It explains how to install the connector, import it, and use functions like fetchall(), fetchone(), execute queries to retrieve, insert, update, delete and manipulate data in database tables. It also discusses SQL commands like aggregation, having, group by and order by clauses.

Uploaded by

Om Mishra
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
100% found this document useful (1 vote)
101 views4 pages

Python SQL Database Connectivity Guide

This document discusses database connectivity in Python. It provides steps to connect Python to an SQL database using the mysql.connector package. It explains how to install the connector, import it, and use functions like fetchall(), fetchone(), execute queries to retrieve, insert, update, delete and manipulate data in database tables. It also discusses SQL commands like aggregation, having, group by and order by clauses.

Uploaded by

Om Mishra
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
  • Chapter 12: Interface Python with an SQL database
  • Chapter 13: SQL commands

COMPUTER SCIENCE

Q.11) What is the role of Django in website design?


Ans:-Django is a high level python web framework, designed to help build complex web applications simply and [Link]
makes it easier to build better web apps quickly and with less code.
Q.12)Write the difference between GET and POST method.
Ans:-A web browser may be the client and the application on a computer that hosts the website may be the server:(i)GET:To request
data from the server
(ii)POST:To submit data to be processed to the server

Chapter 12: Interface Python with an SQL database


Database connectivity-Database connectivity refers to connection and communication between an application and a database system.
[Link]-Library or package to connect from python to MySQL.
Command to install connectivity package:- pip install mysql-connector-python
Command to import connector:- import [Link]
Steps for python MySQL connectivity
1 . Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import [Link]
Multiple ways to retrieve data:
fetchall()-Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples)
fetch many (size)-Fetch the next set of rows of a query result, returning a sequence of sequences. It will return number of
rows that matches to the size argument.
fetchone()-Fetch the next row of a query result set, returning a single sequence or None when no more data is available
Functions to execute SQL queries
#CREATE DATABASE
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345")
mycursor=[Link]()
[Link]("CREATE DATABASE SCHOOL")
# SHOW DATABASE
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345")
mycursor=[Link]()
[Link]("SHOW DATABASE")
for x in mycursor:
print (x)
# CREATE TABLE
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("CREATE TABLE FEES (ROLLNO INTEGER(3),NAME VARCHAR(20),AMOUNT INTEGER(10));")
# SHOW TABLES
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("SHOW TABLES")
for x in mycursor:
print(x)
#DESCRIBE TABLE
import [Link]

68
COMPUTER SCIENCE

mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("DESC STUDENT")
for x in mycursor:
print(x)
# SELECT QUERY
import [Link]
conn=[Link](host="localhost",user="root",passwd="12345",database="student")
c=[Link]()
[Link]("select * from student")
r=[Link]()
while r is not None:
print(r)
r=[Link]()
#WHERE CLAUSE
import [Link]
conn=[Link](host="localhost",user="root",passwd="12345",database="student")
if conn.is_connected==False:
print("Error connecting to MYSQL DATABASE")
c=[Link]()
[Link]("select * from student where marks>90")
r=[Link]()
count=[Link]
print("total no of rows:",count)
for row in r:
print(row)
# DYNAMIC INSERTION
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
[Link]("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m))
[Link]()
print([Link],"RECORD INSERTED")
# UPDATE COMMAND
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
[Link]()
print([Link],"RECORD UPDATED")
# DELETE COMMAND
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("DELETE FROM STUDENT WHERE MARKS<50")
[Link]()
print([Link],"RECORD DELETED")
# DROP COMMAND
import [Link]
mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("DROP TABLE STUDENT")
# ALTER COMMAND
import [Link]
69
COMPUTER SCIENCE

mydb=[Link](host="localhost",user="root",passwd="12345",database="student")
mycursor=[Link]()
[Link]("ALTER TABLE STUDENT ADD GRADE CHAR(3)")

Chapter -12 Data Base Connectivity (Questions and answers)

(1 mark question)
Q.1.1 What is database.
Ans. The database is a collection of organized information that can easily be used, managed, update, and they are
classified according to their organizational approach.
Q.1.2 Write command to install connector.
Ans. pip install mysql-connector-python
Q.1.3 Write command to import connector.
Ans. import [Link]
(2 mark question)
Q.2 write the steps of connectivity between SQL and Python
Ans. import,connect,cursor,execute

Q.3 What is result set? Explain with example.


Ans. Fetching rows or columns from result sets in Python. The fetch functions in the ibm_db API can iterate through
the result set. If your result set includes columns that contain large data (such as BLOB or CLOB data), you can
retrieve the data on a column-by-column basis to avoid large memory usage.

Q.4 Use of functions in connectivity - INSERT, UPDATE, DELETE, ROLLBACK


Ans.

Environment Description
Variables

INSERT It is an SQL statement used to create a record into a table.

UPDATE It is used update those available or already existing record(s).

DELETE It is used to delete records from the database.

ROLLBACK It works like "undo", which reverts all the changes that you have made.

Q.5 Write code for database connectivity


Ans. # importing the module
import [Link]
# opening a database connection
conn = [Link] ("localhost","testprog","stud","PYDB")
# define a cursor object
mycursor = [Link]
# drop table if exists
70
COMPUTER SCIENCE

[Link]("DROP TABLE IF EXISTS STUDENT”)


# query
sql = "CREATE TABLE STUDENT (NAME CHAR(30) NOT NULL, CLASS CHAR(5), AGE INT,
GENDER CHAR(8), MARKS INT)"
# execute query
[Link](sql)
# close object
[Link]()
# close connection
[Link]()
Q.6 Which method is used to retrieve all rows and single row?
Ans:-Fetchall(),fetchone()
Q.7 Write python-mysql connectivity to retrieve all the data of table student.
Ans:-import [Link]
mydb=[Link](user="root",host="localhost",passwd="123",database="inservice")
mycursor=[Link]()
[Link]("select * from student")
for x in mycursor:
print(x)
-------------------------------------------------------------------------------------------------------------------------------------------------------------

Chapter 13: SQL commands: aggregation functions – having, group by, order by
• ORDER BY Clause: You can sort the result of a query in a specific order using ORDER BY clause. The ORDER BY clause allow
sorting of query result by one or more columns. The sorting can be done either in ascending or descending order.
Note: - If order is not specified then by default the sorting will be performed in ascending order.
e.g., Select * from emp order by deptno
Three methods of ordering data are:
1. Ordering data on single column.
2. Ordering data on multiple column.
3. Ordering data on the basis of an expression
• Aggregate Functions: These functions operate on the multiset of values of a column of a relation, and return a value
avg: average value,
min: minimum value ,
max: maximum value ,
sum: sum of values ,
count: number of values
These functions are called aggregate functions because they operate on aggregates of tuples. The result of an aggregate function is
a single value.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno
• GROUP BY Clause: The GROUP BY clause groups the rows in the result by columns that have the same values. Grouping is
done on column name. It can also be performed using aggregate functions in which case the aggregate function produces single
value for each group.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno
• HAVING Clause: The HAVING clause place conditions on groups in contrast to WHERE clause that place conditions on
individual rows. While WHERE condition cannot include aggregate functions, HAVING conditions can do so.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno having deptno=10;
Select job, count (*) from emp group by job having count (*) <3;

Revision of MySQL:-

Field: Set of characters that represents specific data element.


Record: Collection of fields is called a record. A record can have fields of different data types.
File: Collection of similar types of records is called a file.
Table: Collection of rows and columns that contains useful data/information is called a table

71

Common questions

Powered by AI

A database cursor in SQL/Python connectivity acts as a pointer that enables the execution of queries and traversal of database records. When a cursor is created from a connection, it allows SQL commands to be executed programmatically. For instance, to execute a command, the cursor's `execute()` method is called, which sends the SQL statement to the database. Cursors also provide methods like `fetchall()`, `fetchone()`, and `fetchmany()` to retrieve query results. They handle database rows systematically, managing how queries extract, update, or navigate through data sets, which is crucial for maintaining data integrity and functionality within an application .

In Python's database interaction, fetch methods serve different purposes for retrieving data from query results. `fetchall()` retrieves all rows from the current query and returns them as a sequence of tuples, suitable when the dataset is small and manageable in memory. `fetchmany(size)` fetches the next set of rows up to the specified size, allowing flexible memory usage by controlling the batch size of data retrieved at once. `fetchone()` extracts a single row from the result, useful in iterating over large datasets row by row. These methods optimize data retrieval and management based on application needs and memory constraints .

Aggregate functions operate on a group of values and return a single value, often used to perform calculations across entire columns in a database. Common aggregate functions include AVG, SUM, COUNT, MIN, and MAX. The GROUP BY clause, meanwhile, organizes result sets into groups based on column values, allowing aggregate functions to apply to each group independently. While aggregate functions perform calculations, GROUP BY is used to define how datasets are partitioned for those calculations. For example, using `GROUP BY deptno` allows calculation of the `SUM(sal)` and `AVG(sal)` for each department in an employee database .

The WHERE and HAVING clauses in SQL serve different purposes for filtering data. WHERE applies conditions to individual rows before grouping, allowing for the exclusion of rows based on non-aggregate column values. HAVING places conditions on the groups themselves and is used in conjunction with GROUP BY to filter groups of data based on aggregate values. While WHERE is used for filtering data early in the query process, HAVING is suited for post-aggregation filtering, enabling analyses on summary data. For example, to filter employees with high salaries, WHERE would exclude individual rows, whereas HAVING could filter departments based on average salary benchmarks .

The INSERT command in SQL is used to add new records to a table. It specifies column values for the new entry, such as `INSERT INTO students (name, age) VALUES ('Alice', 23)`, which adds a new student to the table. Conversely, the UPDATE command modifies existing records, updating specified columns in records that meet a condition. For example, `UPDATE students SET age = 24 WHERE name='Alice'` changes Alice's age. Both commands are integral for database manipulation; INSERT adds new data, while UPDATE manages and adjusts existing data entries .

A 'result set' in SQL refers to the collection of rows that result from executing a query. It can include entire columns or specific selections based on query constraints. In Python, result sets can be efficiently iterated using fetch methods such as `fetchall()`, `fetchmany()`, and `fetchone()`, which respectively retrieve all rows, a specified number of rows, or a single row from the query outcome. Efficient iteration is crucial, especially for large databases, to manage memory usage and speed. For example, using `fetchone()` in a loop processes rows individually, minimizing memory consumption compared to loading a full result set at once .

GET and POST are HTTP methods used in web development for different purposes. GET is used to request data from a server and can be cached and bookmarked, but it should not be used for sensitive data as it appends data to the URL. POST, on the other hand, is used to submit data to be processed to a server. It is more secure for sensitive data since it does not append data to the URL and can handle larger data submissions. GET should be used for retrieving data where security isn't a concern, while POST is preferred for sending sensitive data and large form submissions .

Establishing a data connection between Python and an SQL database involves several steps and prerequisites. Firstly, ensure Python and MySQL databases are installed. With internet connectivity, use the command `pip install mysql-connector-python` to install the MySQL connector library facilitating connectivity. In Python, import this connector using `import mysql.connector`. Establish a connection to the database with `mysql.connector.connect()`, typically specifying parameters like host, user, password, and database name. Once connected, create a cursor object to execute queries and manage result sets using methods like `execute()`, `fetchall()`, and `fetchone()` .

The ORDER BY clause in SQL queries sorts the results based on one or more columns either in ascending or descending order. This ordering facilitates improved data analysis by allowing easy identification of trends, rankings, or anomalies. It is particularly beneficial in scenarios such as reporting where ordering a list by sales figures can highlight top-performing products, or in academic results where students are ranked by their marks. Without specifying an order, data might appear randomly, complicating analysis tasks that rely on structured indexing .

Django is a high-level Python web framework that enhances the efficiency of building web applications by providing an all-in-one package that simplifies the development process. It adheres to the principle of DRY (Don't Repeat Yourself), reducing the amount of code developers need to write. Django includes pre-built modules for common tasks such as authentication, database interaction, and URL routing, enabling rapid application development and maintaining cleaner codebases. Its ORM (Object-Relational Mapping) allows developers to interact with databases seamlessly, making it easier to build database-driven applications .

68
COMPUTER SCIENCE 
Q.11) What is the role of Django in website design?
Ans:-Django is a high level python web framework, de
69
COMPUTER SCIENCE 
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student") 
mycursor=m
70
COMPUTER SCIENCE 
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=my
71
COMPUTER SCIENCE 
mycursor.execute("DROP  TABLE  IF EXISTS STUDENT”)
# query 
sql = "CREATE TABLE STUDENT (NAME CHAR(30) N

You might also like