Thursday, April 16, 2020

SQL Functionalities in OOP C++ (Part 4/4)


Order by increasing CGPA:
If we want to sort our data in ascending or descending order according to a particular column then Order by statement we can use in SQL. We can use the keyword DSC to sort in descending and ASC to sort in ascending order.Here in our project we sort in ascending order using keyword ASC with a particular column of CGPA from our created table.

Code:

cout<<”order by inc order of CGPA”;
query=”SELECT *FROM STUDENT ORDER BY CGPA ASC; ”;
/*execute sql statement*/ rc=sqlite3_exec(DB,query.c_str(),callback,NULL,&messageError); if(rc!=SQLITE_OK

{
fprintf(stderr,”SQL error:%s\n”),messageError); sqlite3_free(messageError);
else
{
fprintf(stdout,”operation successful”);
}

Output:


Group names by CGPA:
The group by statement groups the rows that have the same values into summary rows.in our project we group the names according to CGPA at output we get name and CGPA of that particular student.

Code:
cout<<”\n Group by CGPA\n”;
query=”SELECT NAME,SUM(CGPA) FROM STUDENT GROUP BY NAME;”;
rc=sqlite3_exec(DB,query.c_str(),callback,NULL,&messageError); if(rc!=SQLITE_OK

{
fprintf(stderr,”SQL error:%s\n”),messageError); sqlite3_free(messageError);
else
{
fprintf(stdout,”operation successful”);
}
Output:




Applications:

The project finds the application for managing the large database like Employee records,Student records,Library management system etc.
 Conclusion:
In our project we have performed various functions of SQL like create a table,delete,insert,sort,search,modify and group by using C++.And came to know how large data can be easily managed by SQL functions.

Amarja Chede
K10

With this we conclude our Blog series!

You can find all documents related to our Course Project in the links given below.

CP Title : SQL functionalitiy in OOP C++

Description: 
Implementation of the following SQL functions in OOP C++ on a database of Student Information
1.Insert Record
2.Delete Record
3.Search Record
4.Modify Record
5.Group by
6.Order by





Topic1
Smruti Khire 
TY K 
Roll no:38
Gr No: 1710206
Video Link: https://drive.google.com/open?id=1CgJZZls-NsPPzJ2m2v3QNP2kJNWm4uvJ

Topic2
Rishita Jaiswal
TY K
Roll No:28
Gr No:1710413
Video Link: https://drive.google.com/open?id=1-nZI5yj_qLy73lTl9KLbgKkK8tHZ95gD

Topic3
Diksha Avhad
TY K
Roll No:3

Gr.No:182058
Video Link: https://drive.google.com/open?id=1fGWsvXYLHGc77-URXjjNPvgGtPlen1Td

Topic4
Amarja Chede
TY K
Roll no:10
Gr.No:182072

Thank you!

SQL Functionality in OOP C++ (Part 3/4 )


Delete Record –
To delete the record or rows or columns in SQL , we can use directly the query but as we are using same functionality in cpp .We need to first create record and then by including SQL libraries in code blocks following with delete record code ,delete function is implemented in our project.

Code-

cout<<"\nDelete Operation\n";

query = "DELETE FROM STUDENT WHERE ID = 2;";
exit = sqlite3_exec(DB, query.c_str(), callback, 0, &messaggeError);
if (exit != SQLITE_OK) {
std::cerr << "Error DELETE" << std::endl;
sqlite3_free(messaggeError);
}
else
std::cout << "Record deleted Successfully!" << std::endl;

Output-




Search –

Using this function of SQL ,we can search any element or elements from the given record and can display it. This is done similarly, in code blocks using SQLite library. Following code will explain the functionality .

Code-

cout<<"\nSearch Operation\n";

string data("CALLBACK FUNCTION");
/* Create merged SQL statement */
query = "SELECT * FROM STUDENT WHERE ID = 20;";

/* Execute SQL statement */
int rc = sqlite3_exec(DB, query.c_str(), callback, (void*)data.c_str(), NULL);
if (rc != SQLITE_OK)
cerr << "Error SELECT" << endl;
else {
cout << "Operation OK!" << endl;   }


Output-



Modify Record-

As name suggest, modify means to make changes and get it replaced in same record is the functionality of this SQL query. This is done by including terms to be modified in code using codeblocks.


Code-
cout<<"\nModify Record\n";
/* Create merged SQL statement */   
query = "UPDATE STUDENT set CGPA = 0 where ID=20;
 "   "SELECT * from STUDENT";

   /* Execute SQL statement */
  rc = sqlite3_exec(DB, query.c_str(), callback, (void*)data.c_str(), NULL);   

 if( rc != SQLITE_OK )
{   
   fprintf(stderr, "SQL error: %s\n", messaggeError);       sqlite3_free(messaggeError);

   }
else
{   
   fprintf(stdout, "Operation done successfully\n");         }

Output-



Diksha Avhad
K3

SQL Functionality in OOP C++ (Part 2/4)


1) Create Database-
Using this function of SQL, we can connect to an existing database. SQL library is used.It will create and return a database object if the database does not exist. The following C code snippet is used.
Code-
sqlite3* DB;
int exit = 0;
exit = sqlite3_open("student.db", &DB);
if (exit) {
            std::cerr << "Error open DB " << sqlite3_errmsg(DB) << std::endl;
            return (-1);
            }
else
            std::cout << "Opened Database Successfully!" << std::endl;          

Output-





2)Create Table-
  
Using this function of SQL, we can create a table in the previously created database. SQL library is used. A table to enter student information is created. The following code snippet is will explain this functionality.

Code-
std::string sql = "CREATE TABLE STUDENT("
                                                            "ID INT PRIMARY KEY       NOT NULL, "
                                                            "NAME                       TEXT NOT NULL, "
                                                            "SURNAME               TEXT NOT NULL, "
                                                            "AGE              INT     NOT NULL, "
                                                            "BRANCH      CHAR(50), "
                                                            "CGPA                        REAL );";

            char* messaggeError;
            exit = sqlite3_exec(DB, sql.c_str(), NULL, 0, &messaggeError);

            if (exit != SQLITE_OK) {
                        std::cerr << "Error Create Table" << std::endl;
                        sqlite3_free(messaggeError);
            }
            else
                        std::cout << "Table created Successfully" << std::endl;

Output-



3) Insert Record-

Using this function of SQL, we can create records in the student table. This is done similarly in code blocks using SQLite library. Following code snippet is used to explain this functionality.

Code-
cout << "STATE OF TABLE BEFORE INSERT" << endl;

sqlite3_exec(DB, query.c_str(), callback, NULL, NULL);
string sql(
"INSERT INTO STUDENT VALUES(1, 'STEVE', 'GATES', 19, 'EnTC',10);"
"INSERT INTO STUDENT VALUES(2, 'BILL', 'ALLEN', 20, 'CS',7);"
"INSERT INTO STUDENT VALUES(3, 'PAUL', 'JOBS', 24, 'CS',8);"
"INSERT INTO STUDENT VALUES(4, 'RISHITA', 'JAISWAL', 20,'CS',9);"
"INSERT INTO STUDENT VALUES(5, 'AMARJA', 'CHEDE', 21, 'CHEM',8);"
"INSERT INTO STUDENT VALUES(6, 'SMRUTI', 'KHIRE', 22, 'CHEM',9.5);"
"INSERT INTO STUDENT VALUES(7, 'DIKSHA', 'AVHAD', 20, 'ENTC',9);"
"INSERT INTO STUDENT VALUES(8, 'SHAMLI', 'BAJAD', 19, 'ENTC',8);"
"INSERT INTO STUDENT VALUES(9, 'SAYLI', 'AHER', 20, 'IT',7);"
"INSERT INTO STUDENT VALUES(10, 'JYOTI', 'JAGTAP', 21, 'ENTC',6);"
"INSERT INTO STUDENT VALUES(11, 'NUTAN', 'AHIRE', 18, 'CS',7);"
"INSERT INTO STUDENT VALUES(12, 'PRATIBHA', 'MHASALE', 21, 'CIVIL',9);"
"INSERT INTO STUDENT VALUES(13, 'VRUSHALI', 'PATIL', 19, 'IT',8);"
"INSERT INTO STUDENT VALUES(14, 'AJAY', 'RAJPUT', 20, 'ENTC',9);"
"INSERT INTO STUDENT VALUES(15, 'PRATHAMESH', 'KHAIRNAR', 20, 'ENTC',9);"
"INSERT INTO STUDENT VALUES(16, 'SAGAR', 'PANDEY', 21, 'MECH',7);"
"INSERT INTO STUDENT VALUES(17, 'MAHESH', 'UGALE', 21, 'ELEX',8);"
"INSERT INTO STUDENT VALUES(18, 'SHUBHAM', 'AHIRE', 19, 'CIVIL',7);"
"INSERT INTO STUDENT VALUES(19, 'ASHOK', 'AMBTE', 29, 'IT',8);"
"INSERT INTO STUDENT VALUES(20, 'ANUJ', 'KHAIRNAR', 19, 'CS',8);"
);

exit = sqlite3_exec(DB, sql.c_str(), callback, 0, &messaggeError);
if (exit != SQLITE_OK) {
std::cerr << "Error Insert" << std::endl;
sqlite3_free(messaggeError);
}
else
{
std::cout << "Records created Successfully!" << std::endl;
}

Output-








Rishita Jaiswal
K 28






Sunday, April 12, 2020

OOP Course Project -SQL Functionality in OOP C++ (Part 1/4 )



In this part of our blog we will be explaning the implementation of our Course Project done as a part of the OOP Course.

SQL (Structured Query Language) is a way to communicate with a database that lets
you define a query to modify and control the data. We have developed the project using C++ so the accessing of SQL functions is done through SQLite Library.

We have implemented the following functions on a database of 20 Students (custom made database) with the record consisting of their ID, Name, Surname, Branch and CGPA :
1. Insert Record
2. Delete Record
3. Search Record
4. Modify Record
5. Order by
6. Group by

A breif insight into the SQLite Library:

SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is free for use for any purpose, commercial or private. Ordinary disk files can be easily read and written by SQLite because it does not have any separate server like SQL.The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems.

Basic routines in SQLite:

sqlite3_open (const char *filename, sqlite3 **ppDb)
This routine opens a connection to a SQLite database file and returns a database connection object
for other SQLite programs.

sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)
This routine provides a shortcut to execute SQL commands, which are provided by the sql
parameter and can consist of multiple SQL commands.

sqlite3_close(sqlite3*)
This routine closes the database connection opened before calling sqlite3_open(). All connection-
related statements should be completed before the connection is closed.

The Callback function
The callback function provides a SELECT The way the statement gets the result.
It is stated as follows:
typedef int (*sqlite3_callback)(
void*, /* Data provided in the 4th argument of sqlite3_exec() */
int,
/* The number of columns in row */
char**, /* An array of strings representing fields in the row */
char** /* An array of strings representing column names */
);

If the above callback is in sqlite_exec() As the third parameter in the program, SQLite will call
this callback function for each record processed in each SELECT statement executed within the
SQL parameter.

This was a basic introduction of the functionality and use of SQLite in our project.
The website referred for this part is : https://www.welookups.com/sqlite/sqlite-c-cpp.html

In the upcoming blogs we will be going through the practical execution of the above mentioned routines to develop the project.

Smruti Khire
K 38

Exception Handling in Java-Part 2



The error that occurs during execution which leads to disturb in flow of execution is nothing but the exception .Exceptions can be of any type and the ways to handle that exception are called as exception handling.

Checked and unchecked are the types of exceptions in java.

Checked exceptions: a program has to catch and handle that exception is called a checked exception .In the source code only checked exceptions have to be declared.Checked exceptions are declared by the compiler at compile time.

Unchecked exception: unchecked exceptions are not checked by the compiler. in the program unchecked exceptions are not specified and it does not cause compilation error. The unchecked exception handled at run time


some of the exceptions in java are as follows.

NullPointerException:

If we are using any pointer to referring to the member but that member is of null object then this exception thrown as Null means nothing it means it represents nothing.NullPointerException it is an unchecked exception.

ex-
class NullPointer_code
{
public static void main(String args[])

{

try {

String a = null; System.out.println(a.charAt(0));
} catch(NullPointerException e) { System.out.println("NullPointerException thrown..");
}
}
}

Output: NullPointerException thrown..

NumberFormatException:

Suppose we have created one class in which we are assigning a string value to integer data type and if that method is not able to convert that string into numeric format then This exception is raised.NumberFormatException it is an unchecked exception.
class NumberFormat_code

{
public static void main(String args[])
{
try {
int num = Integer.parseInt ("abcd") System.out.println(num);
} catch(NumberFormatException e) { System.out.println("Number format exception thrown");
}
}
}
Output: Number format exception thrown

RuntimeException:

When any exception occurs during runtime then it is represented by RuntimeException This represents any exception which occurs during runtime.RuntimeException it is an unchecked exception.
ex-
public class MyExceptionTest { public void testRuntimeException () { throw new MyException();
}
 public static void main(String[] args) { try {
new MyExceptionTest().testRuntimeException();
 } catch(Exception e) { System.out.println(e.getClass().getName());
}
}
}
class MyException extends RuntimeException { public MyException() {
super();
}
}

Output: MyException

StringIndexOutOfBoundsException:

It is thrown from String class methods to show an index is either negative than the size of the string.StringIndexOutOfBoundsException it is an unchecked exception.And it extends a Run time exception.

NoSuchFieldException:

Suppose if our class does not contain a field or variable and we are trying to call that then it is thrown that exception.

NoSuchMethodException:

The exception is thrown when we access a method which is not found. It means suppose we try to dynamically use a method on a class, and the method does not actually exist then also it gives NoSuchMethodException.NoSuchMethodException it is a checked exception.

Amarja Chede
K10

Exception Handling In Java-Part 1



Exceptions are unplanned or unwanted situations ,which gets occurred during execution of programming in run time or compile time and disturbs the flow of execution.

Based on class libraries, Java has various types of exceptions i.e built-in exceptions. Even user defined exceptions are present in java.

Built-in exceptions are due to libraries so they are suitable to explain certain error situations.
Types of Built-in exception-



1.     Arithmetic Exception –
Arithmetic means numbers,so these are occurred due to numbers .It is unchecked error and then exception occurs like –when divide by 0 causes mathematical problem at run time as it cannot handle this situation.During that time arithmetic exception is thrown.

Code-

class ArithmeticException_Demo
{
    public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a/b;  // cannot divide by zero
            System.out.println ("Result = " + c);
        }
        catch(ArithmeticException e) {
            System.out.println ("Can't divide a number by 0");
        }
    }
}

Output-

Can’t divide a number by 0


2.     ArrayIndexOutOfBoundsException –
Whenever array elements are entered above specified length it gives exception which is called the ‘ArrayIndexOutOfBoundsException'.
ArrayIndexOutOfBoundsException implements a ‘serializable’ interface i.e serial by serial entry and derives from the ‘indexOutOfBoundsException’ which in turn is derived from the RuntimeException class which is a subclass of the ‘exception’ class. It is unchecked exception and does not need to be called from method explicitly.
Code-
Example 1-
class Main { 
    public static void main(String[] args) { 
        //array of subjects. There are 5 elements.
        String[] subjects = {"Maths","Science","French","Sanskrit", "English"};  

        //for loop iterates from 0 to 5
        for(int i=0;i<=subjects.length;i++) {      
                        System.out.print(subjects[i] + " ");     
        } 
    }
Output-
Maths Science French Sanskrit English Exception in thread “main”java.lang.ArrayIndexOutOfBoundsException : 5
    At Main.main(Main.java:9)
Simply this exception indicates array has accessed been accessed with illegal index i.e index isgreater than or equal to size of array or negative.
Example 2-
class ArrayIndexOutOfBound_Demo
{
    public static void main(String args[])
    {
        try{
            int a[] = new int[5];
            a[6] = 9;
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println ("Array Index is Out Of Bounds");
        }
    }
}

Output-
Array Index is out of Bounds.
3.    ClassNotFoundException
As name given,class not found means class definition npt available or found then this exception occurs.
java.lang.classNotFoundException in Java is a subclass of Exception and occurs when Java Virtual Machine tries to load  class and doesn't found it.

 4.     FileNotFoundException-

According to name file not found this exception occurs when file is not present or cannot be accesed. If in code it is written to get path of file and file on same path is not present then this exception occurs.

private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        //HACK
        //FileURLMapper p = new FileURLMapper (url);
        File p = new File(url.getPath());
 
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return new JarFile (p.getPath());
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}

5.     IOException-

IOExceptions are thrown when there is any input / output file operation issues while application perform certain tasks accessing the files. IOException is a checked exception and application developer has to handle in correct and proper manner. IOException has many subcases like filenotfoundexception as this occurs when file is not present and similarly it gives input missing which cause IOException.

Code-

static ArrayList<BufferedImage> getFrames(File gif) throws IOException {
    ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
    ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
    ir.setInput(ImageIO.createImageInputStream(gif));
    for (int i = 0; i < ir.getNumImages(true); i++) {
        frames.add(ir.read(i));
    }
    // Release resources for Garbage Collection
    ir.dispose();
    return frames;
} 



6.     InterruptedException-

    Thrown when a thread is waiting, sleeping,or otherwise occupied, and the thread is                              interrupted,either before or during the activity. Usually used to test whether the current thread has        been interrupted, and if so, to immediately throw this exception.

      if (Thread.interrupted())  // Clears interrupted status!
       throw new InterruptedException();



Diksha Avhad
K-3