📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 284question

DATA MANIPULATION THROUGH SQL · Part 11

Chapter 4: 6 · COMPUTER SCIENCE

and displayed the result with the column headings. Example . - import sqlite3 connection = sqlite3.connect("Academy.db") cursor = connection.cursor() cursor.execute("""DROP TABLE Appointment;""") = """ CREATE TABLE Appointment(rollnointprimarkey,Dutyvarchar( ),age int)""" cursor.execute( ) = """INSERT INTO Appointment (Rollno,Duty ,age ) VALUES (" ", "Prefect", " ");""" cursor.execute( ) = """INSERT INTO Appointment (Rollno, Duty, age) VALUES (" ", "Secretary", " ");""" cursor.execute( ) # never forget this, if you want the changes to be saved: connection.commit() cursor.execute ("SELECT student.rollno,student.sname, Appointment.Duty, Appointment.Age FROM student,Appointment where student.rollno=Appointment.rollno") #print (cursor.description) to display the field names of the table co = [i[ ] for i in cursor.description] print(co) # Field informations can be read from cursor.description. result = cursor.fetchall() for r in result: print(r) OUTPUT ['Rollno', 'Sname', 'Duty', 'age'] ( , 'Akshay', 'Prefect', ) ( , 'Aravind', 'Secretary', ) .

cursor. description contain the details of each column headings .It will be stored as a tuple and the first one that is (zero) index refers to the column name. From index onwards the values of the column(Records) are refered. Using this command you can display the table’s Field names.

Note 12th Computer Chapter - - Data Manipulation Through SQL Integrating Query With Csv File . You can even store the query result in a CSV file. This will be useful to display the query output in a tabular format. In the following example (EXAMPLE .

- ) Using Python script the student table is sorted “gender” wise in descending order and then arranged the records alphabetically. The output of this Query will be written in a CSV file called “SQL.CSV”, again the content is read from the CSV file and displayed the result. Example . - import sqlite3 import csv # CREATING CSV FILE d=open('c:/pyprg/sql.csv','w, newline= ' ') c=csv.writer(d) connection = sqlite3.connect("Academy.db") cursor = connection.cursor() cursor.execute("SELECT * FROM student ORDER BY GENDER DESC,SNAME") # WRITING THE COLUMN HEADING co = [i[ ] for i in cursor.description] c.writerow(co) data=cursor.fetchall() for item in data: c.writerow(item) d.close() # Reading the CSV File with open('c:/pyprg/sql.csv', "r") as fd: for line in fd: line = line.replace("\n", "") print(line) cursor.close() connection.close() OUTPUT Rollno,Sname,Grade,gender,Average, , Akshay, B, M, .

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →