Wednesday, April 1, 2015

JDBC Basics

Creating JDBC Application:

There are six steps involved in building a JDBC application which I'm going to brief in this tutorial:

Import the packages:

This requires that you include the packages containing the JDBC classes needed for database programming. The package needed for JDBC is java.sql.*

Register the JDBC driver:

This requires that you initialize a driver so you can open a communications channel with the database. 
The driver for MySql is "com.mysql.jdbc.Driver" 
The driver for Oracle is "oracle.jdbc.driver.OracleDriver"

Open a connection:

This requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database. This method requires Database URL, username, Password.

Execute a query:

This requires using an object of type Statement or PreparedStatement for building and submitting an SQL statement to the database
Extract data from result set:
This step is required in case you are fetching data from the database. You can use the appropriate ResultSet.getXXX() method to retrieve the data from the result set 

Clean up the environment:

You should explicitly close all database resources versus relying on the JVM's garbage collection 

Monday, March 30, 2015

SQL Syntax

select columnnames from tablename where condition;
Eg:
SELECT empid,empname,email,salary FROM employee WHERE empid=1;

insert into tablename(col1,col2...) values(val1,val2,...)
Eg:
INSERT INTO employee(empid,empname,email,salary) VALUES(1,'xxxx','xxx@gmail.com',10000);


delete from tablename where condition;
Eg:
DELETE FROM employee WHERE empid=1;


update employee set empname='cccc' where empid=1;

Monday, March 23, 2015

IO Stream

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

OutputStream

Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
InputStream

Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.

FileInputStream and FileOutputStream (File Handling)

In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.

import java.io.FileOutputStream;

class Test {
public static void main(String args[]) {
try {
FileOutputStream fout = new FileOutputStream("C:\\abc.txt"); // It is creating a new file
String s = "Sachin Tendulkar is my favourite player!!!!!";
byte b[] = s.getBytes();// converting string into byte array
fout.write(b); //Sending Byte[] to write method in FileOutputStream
//fout.close();  
/*FileOutputStream fout1 = new FileOutputStream("C:\\abc.txt");*/
String str = "New char";
byte[] b1 = str.getBytes();
fout.write(b1);
System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}

Tuesday, March 17, 2015

Queue

package com.queuesample;

import java.util.*;

public class QueueDemo {

public static void main(String[] args) {

System.out.println( "Queue in Java" );
System.out.println("-----------------------" );
System.out.println("Adding items to the Queue"  );
// Creating queue would require you to create instance of LinkedList
// and assign
// it to Queue
// Object. You cannot create an instance of Queue as it is abstract
Queue queue = new LinkedList();

// you add elements to queue using add method
queue.add("Java");
queue.add(".NET");
queue.add("Javascript");
queue.add("HTML5");
queue.add("Hadoop");

System.out.println( "Items in the queue..." + queue );
System.out.println("Before removing "+queue.element());
// You remove element from the queue using .remove method
// This would remove the first element added to the queue, here Java
System.out.println("remove element: " + queue.remove() );

// .element() returns the current element in the queue, here when "java"
// is removed
// the next most top element is .NET, so .NET would be printed.
System.out.println("retrieving element: " + queue.element()  );

// .poll() method retrieves and removes the head of this queue
// or return null if this queue is empty. Here .NET would be printed and
// then would
// be removed
// from the queue
System.out.println("remove and retrieve element, null if empty: "
+ queue.poll() );
System.out.println("After the polling method "+queue.element());

// .peek() just returns the current element in the queue, null if empty
// Here it will print Javascript as .NET is removed above
System.out.println("retrieve element, null is empty " + queue.peek()
);
PriorityQueue priorityQueue = (PriorityQueue)queue;
}
}

Monday, March 16, 2015

Java API - Predefined Packages

Package NameExample ClassesFunctionality (Purpose)
java.langSystem, String, Object, Thread, Exception etc.These classes are indispensable for every Java program. For this reason, even if this package is not imported, JVM automatically imports.
java.utilThese are called as utility (service) classes and are used very frequently in coding.
java.ioFileInputStream, FileOutputStream, FileReader, FileWriter, RandomAccessFile, BufferedReader, BufferedWriter etc.These classes are used in all I/O operations including keyboard input.
java.netURL, ServerSocket, Socket, DatagramPacket, DatagramSocket etc.Useful for writing socket programming (LAN communication).
java.appletAppletContext, Applet, AudioStub, AudioClip etcRequired for developing applets that participate on client-side in Internet (Web) programming.
java.awtButton, Choice, TextField, Frame, List, Checkbox etc.Essential for developing GUI applications.
java.awt.eventMouseListener, ActionListener, ActionEvent, WindowAdapter etc.Without these classes, it is impossible to handle events generated by GUI components
java.sqlDriverManager, Statement, Connection, ResultSet etcRequired for database access in JDBC applications.

Thursday, March 12, 2015

HashMap Example

package com.mapsample;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {

public static void main(String[] args) {

Hashtable<String, String> hashtableobj = new Hashtable<String, String>();
hashtableobj.put("Alive is ", "awesome");
hashtableobj.put("Love", "yourself");
hashtableobj.put("Clean", "World");
//hashtableobj.put(null,"Testing");

System.out.println("Hashtable object output :" + hashtableobj);

HashMap hashmapobj = new HashMap();
hashmapobj.put("Alive is ", "awesome");
hashmapobj.put("Love", "yourself");
hashmapobj.put("Clean", "World");
//hashmapobj.put(null,"Testing");
System.out.println("HashMap object output :" + hashmapobj);

Set keys = hashmapobj.keySet();
System.out.println(keys);
Iterator itr = keys.iterator();
while(itr.hasNext())
{
String key = itr.next().toString();
System.out.println("Key is "+key+" and value is "+hashmapobj.get(key));
}





// Create a hash map
/* HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double) hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));

TreeMap treeMap = new TreeMap();

treeMap.put("Zara", new Double(3434.34));
treeMap.put("Mahnaz", new Double(123.22));
treeMap.put("Ayan", new Double(1378.00));
treeMap.put("Daisy", new Double(99.22));
treeMap.put("Qadir", new Double(-19.08));
System.out.println(treeMap);


*/ }
}

Map

The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface.
A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.


The java.util.SortedMap interface is a subtype of the java.util.Map interface, with the addition that the elements stored in the map are sorted internally.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method TreeMap.descendingKeySet().