Wednesday 27 March 2013

What is a Diamond problem in java? Why multiple inheritance is not supported in java?


Consider a class A has foo() method and then B and C derived from A and has their own foo() implementation.
Now class D derive from B and C using Multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke.
This is called as Diamond problem because structure on this inheritance scenario is similar to four edge diamond.
Also multiple inheritance causes problem in Constructor chaining, Casting.

Can you override static method in Java?


No. We can not override static method in java.
Overriding depends on having an instance of a class.
The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses).
A static method is not associated with any instance of a class so the concept is not applicable.

Can you access non Static variable in Static block?

No. Only static variables can be accessed in static block.

Will finally block execute ,if System.exit is called in try or catch block?

No. Finally block won't run if you call System.exit form try catch.

Will finally block execute ,if a return statement is called in try or catch block?

Yes. The finally block will execute even if there is return statement in try or catch block.

Monday 4 March 2013

What does Class.forName() method do?



  • Method forName() is a static method of java.lang.Class.
  • This can be used to dynamically load a class at run-time.
  • Class.forName() loads the class if its not already loaded.
  • It also executes the static block of loaded class.
  • Then this method returns an instance of the loaded class.
  • So a call to Class.forName('MyClass') is going to do following


                       -Load the class MyClass.
                       -Execute any static block code of MyClass.
                       -Return an instance of MyClass.

  • JDBC Driver loading using Class.forName is a good example of best use of this method.


The driver loading is done like this

Class.forName("org.mysql.Driver"); 

  • All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. 
  • A MySQL JDBC Driver has a static initializer which looks like this:


static { 
    try { 
        java.sql.DriverManager.registerDriver(new Driver()); 
    } catch (SQLException E) { 
        throw new RuntimeException("Can't register driver!"); 
    } 

  • Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.

Sunday 3 March 2013

What are the main steps in java to make JDBC connectivity?


Load the Driver: 
·         First step is to load the database specific driver which communicates with database.

Syntax:          Class.forName(…);

Make Connection: 
·         Next step is get connection from the database using connection object, which is used to send SQL statement also and get result back from thedatabase.

Syntax:          Connection con=DriverManager.getConnection(…);

Get Statement object: 
·         From connection object we can get statement object which is used to query the database

Syntax:         Statement stmt=con.createStatement();

Execute the Query:
·         Using statement object we execute the SQL or database query and get result set from the query.

Syntax:          stmt.executeQuery(…);

Close the connection:
·         After getting resultset and all required operation performed the last step should be closing the database connection.

Syntax:          con.close();

What is Connection pooling? What are the advantages of using a connection pool?


  • A connection pool operates by performing the work of creating connections ahead of time.
  • In the case of a JDBC connection pool, a pool of Connection objects is created at the time the application server starts.
  • These objects are then managed by a pool manager that disperses connections as they are requested by clients and returns them to the pool when it determines the client is finished with the Connection object.
  • When the connection pool server starts, it creates a predetermined number of Connection objects. 
  • A client application would then perform a JNDI lookup to retrieve a reference to a DataSource object that implements the ConnectionPoolDataSource interface.
  • When the client application requests a connection from the ConnetionPoolDataSource, the data source implementation would retrieve a physical connection to the client application.
  • The ConnectionPoolDataSource would return a Connection object that implemented the PooledConnection interface.
  • The PooledConnection interface dictates the use of event listeners. 
  • These event listeners allow the connection pool manager to capture important connection events, such as attempts by the client application to close the connection.
  • When the driver traps a close-connection event, it intercedes and performs a pseudo-close operation that merely takes the Connection object, returns it to the pool of available connection.
  • The operation of the connection pool should be completely transparent to the client application.
  • The triggering of connection events, the manipulation of the object pool, and the creation and destruction of physical connections are all managed by the pool manager.


Context.xml

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" driverClassName="com.mysql.jdbc.Driver"               url="jdbc:mysql://localhost:3306/cdcol"/>

 //This should be added in the servers context,xml file. For example if you are using apache server then the context.xml will be found in C:\apache-tomcat-6.0.26\conf\Context.xml

web.xml

  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

//This should be added in the web.xml of the local project. (Not in server's web.xml).

For implementation example please refer to: 

Download DB values as CSV file with JNDI Connection Pool Method

What are the disadvantages of JDBC?


  • The process of creating a connection, always an expensive, time-consuming operation, is multiplied in these environments where a large number of users are accessing the database in short, unconnected operations.
  • Creating connections over and over in these environments is simply too expensive.
  • When multiple connections are created and closed it affects the performance.

How to call stored procedure using JDBC API?


Stored procedures can be called using CallableStatement class in JDBC API. Below code snippet shows how this can be achieved.

Code Snippet:

            CallableStatement cs = con.prepareCall("{call MY_STORED_PROC_NAME}"); 
            ResultSet rs = cs.executeQuery();  

How to create a stored procedure?


Creating a Stored Procedure:

CREATE PROCEDURE uspGetAddress // Either PROCEDURE of PROC can be used
AS
SELECT * FROM AdventureWorks.Person.Address
GO

Call in SQL:

EXEC uspGetAddress
--or just simply
uspGetAddress

Creating a Stored Procedure with parameters:

CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO

Call in SQL:

EXEC uspGetAddress @City = 'New York'

  • One thing to note is that you cannot use the keyword "GO" in the stored procedure.  
  • Once the SQL Server compiler sees "GO" it assumes it is the end of the batch.
  • Also, you can not change database context within the stored procedure such as using "USE dbName" the reason for this is because this would be a separate batch and a stored procedure is a collection of only one batch of statements.

What is a stored procedure?

Stored Procedure:

  • Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task.
  • Stored Procedures are used to encapsulate a set of operations or queries to execute on database.
  • Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. 

What are the types of statements in JDBC?

The different types of Statements used in JDBC connection are as follows:


JDBC API has 3 Interfaces,
  1. Statement
  2. PreparedStatement
  3. CallableStatement  


Statement
  • This interface is used for executing a static SQL statement and returning the results it produces.
  • The object of Statement class can be created using Connection.createStatement() method.


PreparedStatement

  • A SQL statement is pre-compiled and stored in a PreparedStatement object.
  • This object can then be used to efficiently execute this statement multiple times.
  • The object of PreparedStatement class can be created using Connection.prepareStatement() method.
  • This extends Statement interface.


Exampe Code:

import java.sql.*;

public class TwicePreparedStatement{
  public static void main(String[] args) {
  System.out.println("Twice use prepared statement example!\n");
  Connection con = null;
  PreparedStatement prest;
  try{
  Class.forName("com.mysql.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
  try{
  String sql = "SELECT * FROM movies WHERE year_made = ?";
  prest = con.prepareStatement(sql);
  prest.setInt(1,2002);
  ResultSet rs1 = prest.executeQuery();
  System.out.println("List of movies that made in year 2002");
  while (rs1.next()){
  String mov_name = rs1.getString(1);
  int mad_year = rs1.getInt(2);
  System.out.println(mov_name + "\t- " + mad_year);
                                                }
  prest.setInt(1,2003);
  ResultSet rs2 = prest.executeQuery();
  System.out.println("List of movies that made in year 2003");
  while (rs2.next()){
  String mov_name = rs2.getString(1);
  int mad_year = rs2.getInt(2);
  System.out.println(mov_name + "\t- " + mad_year);
  }
  }
  catch (SQLException s){
  System.out.println("SQL statement is not executed!");
  }
  }
  catch (Exception e){
  e.printStackTrace();
  }
            }
}

CallableStatement

  • This interface is used to execute SQL stored procedures.
  • This extends PreparedStatement interface.
  • The object of CallableStatement class can be created using Connection.prepareCall() method.




Friday 1 March 2013

JDBC: Batch insert in database Java Example Program

Program:


import java.sql.*;
public class JdbcBatchInsert {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);// Disables auto-commit.
st = con.createStatement();
st.addBatch("INSERT INTO person VALUES('4','Komal')");
st.addBatch("INSERT INTO person VALUES('5','Ajay')");
st.addBatch("INSERT INTO person VALUES('6','Santosh')");
st.executeBatch();
String sql = "select * from person";
rs = st.executeQuery(sql);
System.out.println("No  \tName");
while (rs.next()) {
System.out.print(rs.getString(1) + " \t");
System.out.println(rs.getString(2));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

JDBC: Getting Column Names from Database Java Example Program

Program:


import java.sql.*;

public class ColumnName {
public static void main(String[] args) {
System.out.println("Getting Column Names Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "abhi";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM abc");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
System.out.println("Number of Column : "+ col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
System.out.println(col_name);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

JDBC: Change column name in a database table Java Example Program

Program:

import java.io.*;
import java.sql.*;

public class ChangeColumnName {
public static void main(String[] args) {
System.out.println("Change column name in a database table example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/abhi","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
System.out.println("Enter old column name:");
String old_col = bf.readLine();
System.out.println("Enter new column:");
String new_col = bf.readLine();
System.out.println("Enter data type:");
String type = bf.readLine();
int n = st.executeUpdate
("ALTER TABLE "+table+" CHANGE "+old_col+" "+new_col+" "+type);
System.out.println("Query OK, "+n+" rows affected");
}
catch (SQLException s){
System.out.println("Wrong entry!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

JDBC: Batch example in Java


Program:

import java.sql.*;
public class BatchEx {

public static void main (String[] args)  throws Exception     {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
String userName = "root";
String password = "root";
String url ="jdbc:mysql://localhost/abhi";
java.util.Calendar  c=java.util.Calendar.getInstance();
conn = DriverManager.getConnection(url,userName,password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO xyz VALUES(?,?,?,?)");
stmt.setInt(1,15);
stmt.setInt(2,1);
c.clear();  
c.set(2011,9,25);
stmt.setDate(3, new java.sql.Date((c.getTime()).getTime()));
c.set(2011,9,27);
stmt.setDate(4,new java.sql.Date((c.getTime()).getTime()));

stmt.addBatch();
stmt.setInt(1,16);
stmt.setInt(2,2);
c.clear();
c.set(2011,10,12);
stmt.setDate(3,new java.sql.Date((c.getTime()).getTime()));
c.set(2011,10,27);
stmt.setDate(4,new java.sql.Date((c.getTime()).getTime()));
stmt.addBatch();
stmt.executeBatch();
conn.close();
}
}

JDBC: Listing all table name in Database Java Program



Program:

import java.sql.*;

public class AllTableName {
public static void main(String[] args) {
System.out.println("Listing all table name in Database!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "abhi";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
try{
DatabaseMetaData dbm = con.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbm.getTables(null,null,"%",types);
System.out.println("Table name:");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
System.out.println(table);
con.close();
}
}
catch (SQLException s){
System.out.println("No any table in the database");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

JDBC: Adding new column in table example Java Program

Program:

import java.io.*;
import java.sql.*;

public class AddColumn {
public static void main(String[] args) {
System.out.println("Adding new column in table example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/ruth","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
System.out.println("Enter column name:");
String col = bf.readLine();
System.out.println("Enter data type:");
String type = bf.readLine();
int n = st.executeUpdate("ALTER TABLE "+table+" ADD "+col+" "+type);
System.out.println("Query OK, "+n+" rows affected");
}
catch (SQLException s){
System.out.println("Tabel or column or data type is not found!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}