Вы находитесь на странице: 1из 6

Data management :SQL and web server

1 :find the min, max, sum, and average of the marks in a student marks table.

Table:Student_marks

id name Class math english


1 John Deo Four 75 55
2 Max Ruin Three 85 85
3 Arnold Three 55 72
4 Krish Star Four 60 66
5 John Mike Four 60 60
6 Alex John Four 55 75

SQL Queries

mysql> Select Sum(mark) from student;

mysql> Select Min(mark) from student;

mysql> Select Max(mark) from student;

mysql> Select Avg(mark) from student;

Command-

SELECT MIN(mark) as min_mark FROM `student`

SELECT max( mark ) FROM `student`

SELECT id, name, class,( math+english) AS total FROM `student`

SELECT sum(math+english) as total from student

mysql> Select AVG(mark) from student;

mysql> Select AVG(avg) from student Group By class;

2. Find the total no of customers from each country in the table(customer ID,
customer name, country) using group by.

Table: Custmer

Cust_id Cust_name country


1001 Jai kumar India
1002 Max Ruin u.s.a
1003 Ravi kumar India
1004 Ajay kumar india
1005 Krish Star japan
Mysql>SELECT COUNT(cust_Id), Country

FROM Customer

GROUP BY Country

ORDER BY COUNT(Id) DESC

3. write a SQL query to order the (student ID, marks) table in descending order of the marks.

Table:Student_marks

Std_id Std_name Subject marks


1 Ram Science 85
2 Ram English 80
3 Ram Math 70
4 Shayam Math 80
5 Shayam English 70
6 Shayam Science 65
7 Hari Science 90
8 Hari English 80
Mysql>SELECT std_id,
subject,
CASE subject
WHEN 'english' THEN english
WHEN 'math' THEN math
WHEN 'science' THEN science
END marks
FROM student s CROSS JOIN
(
SELECT 'english' subject UNION ALL
SELECT 'math' UNION ALL
SELECT 'science'
)t

ORDER BY name, marks DESC


SELECT name, grad as subject, mark
FROM
(
SELECT name, english as mark, 'english' as grad FROM student
UNION
SELECT name, math, 'math' FROM student
UNION
SELECT name, science, 'science' FROM student
) as t
ORDER BY name, mark DESC

| NAME | SUBJECT | MARKS |


|-----------|--------------|-----------|
| Hari | science | 90 |
| Hari | english | 80 |
| Hari | math | 60 |
| Ram | science | 85 |
| Ram | English | 80 |
| Ram | math | 70 |
| shyam | math | 80 |
| shyam | english | 70 |
| shyam | science | 65 |

4. Integrate SQL with python by importing the mysql module.


demo_mysql_test.py
import mysql.connector

#if this page is executed with no errors, you have the "mysql.connector"
module installed.

demo_mysql_connection.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

print(mydb)

demo_mysql_connection.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

print(mydb)
demo_mysql_create_db.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

#If this page is executed with no error, you have successfully created a database.

demo_mysql_show_databases.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

Run:
C:\Users\My Name>python demo_mysql_show_databases.py
('information_scheme',)
('mydatabase',)
('performance_schema',)
('sys',)

demo_mysql_db_exist.py
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)

#If this page is executed with no error, the database "mydatabase" exists in your
system

5. Write a Django based web server to parse a user request (POST) , and write it to a
CSV file.

Python CSV library


import csv
from django.http import HttpResponse

def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

return response

Streaming large CSV files

import csv

from django.http import StreamingHttpResponse

class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value

def some_streaming_csv_view(request):
"""A view that streams a large CSV file."""
# Generate a sequence of rows. The range is based on the maximum number of
# rows that can be handled by a single sheet in most spreadsheet
# applications.
rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse((writer.writerow(row) for row in rows),
content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
return response

Using the template system


from django.http import HttpResponse
from django.template import Context, loader

def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

# The data is hard-coded here, but you could load it from a database or
# some other source.
csv_data = (
('First row', 'Foo', 'Bar', 'Baz'),
('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"),
)

t = loader.get_template('my_template_name.txt')
c = Context({
'data': csv_data,
})
response.write(t.render(c))
return response

Вам также может понравиться