Showing posts sorted by relevance for query JDBC. Sort by date Show all posts
Showing posts sorted by relevance for query JDBC. Sort by date Show all posts

JDBC: Introduction

  • JDBC is a standard which is designed by Sun Micro Systems.
  • JDBC provides a standard library to access RDBMS (Relational Database Management System).
  • JDBC API allow  Java code to connect wide variety of data bases.

JDBC API supports 4 types of drivers. They are listed below
  1. JDBC-ODBC bridge driver:
  2. The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. Now a days, In production, no one encourage to use this driver.
    Advantages:
    • It is easy to configure or connect database and use.
    Disadvantages:
    • Performance degraded because each JDBC method call is converted into the ODBC function calls.
    • The ODBC driver needs to be installed on the client machine.
  3. Native-API driver (partially java driver):
  4. The Native API driver uses the client-side libraries of the database. In this driver each JDBC method calls converts into native calls of the database API. It is partially written in java.
    Advantage:
    • performance upgraded than JDBC-ODBC bridge driver.
    Disadvantage:
    • Driver dependency. It means, The Native driver needs to be installed on the each client machine.
    • The Vendor client library needs to be installed on client machine..
  5. Network Protocol driver (fully java driver)
  6. The Network Protocol driver uses application server9Middleware). The Middleware layer converts each JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
    Advantage:
    • It is better performer than Native -API Driver.
    • No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
    Disadvantages:
    • Network support is required on client machine.
    • Requires database-specific coding to be done in the middle tier.
    • Network Protocol driver requires database-specific coding to be done in the middle tier, So it expensive to maintain.
  7. Thin driver (fully java driver)
  8. The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.
    Advantage:
    • Widely acceptable driver to connect database
    • Better performance than all other drivers.
No software is required at client side or server side. Disadvantage:
  • Independent driver implementation required for each database. It means, each database has it's own driver implementation.

The following picture describes JDBC Architecture

Steps to connect Database using JDBC API in Java

Steps to connect Database using JDBC API in Java
  1. Load the JDBC Driver:
  2. Class.forName() ,create's a driver instance and register it with the JDBC driver manager. Syntax: Examples: The above examples creates MySQL and OracleDriverdriver instance and register with JDBC.
  3. Define the connection URL
  4. In JDBC, a connection URL specifies the server host, port, and database name with which to establish a connection.
    Syntax: Example
     
    MySQL : jdbc:mysql://localhost:3306/test
    ORACLE : jdbc:oracle:thin:@localhost:1521:xe
    
    In the above example
    • protocol: jdbc
    • database-host :mysql://localhost
    • port : 3306
    • database-name : test.
  5. Establish the connection to Database
  6. The getConnection() method of DriverManager class is used to establish connection with the database.
    With the connection URL, username,and password, a network connection to the database can be established.
    Once the connection is established, database queries can be performed until the connection is closed.
    Syntax: Example:
  7. Create a Statement object
  8. . Creating a Statement object enables you to send queries and commands to the database.
    The createStatement() method of Connection interface is used to create statement.
    Syntax: Example:
  9. Execute a query or update
  10. . Given a Statement object, The execute(),executeQuery(),executeUpdate(), or executeBatch() method of Statement interface is used to execute queries to the database.
    This method returns the object of ResultSet that can be used to get all the records of a table.
    Syntax: Example: The above example describes, how to create and insert records into student table in database.
  11. Process the results.
  12. When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows and columns that you can process by calls to next and various getXxx methods.
    Syntax: Example: The above code snippet is used to display list of names in Student table.
  13. Close the connection.
  14. When you are finished performing queries and processing results, you should close the connection, releasing resources to the database.
    Syntax: Example

ClassNotFoundException vs. NoClassDefFoundError

ClassNotFoundException vs. NoClassDefFoundError
This is a very common question in Java interviews.

Here we will learn to distinguish between two similar, but different problems that can crop up in your code.

Similarities - 

  • ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios. 

Differences - 

  • ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath. 
  • NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time. 

Let us see some examples -

ClassNotFoundException 

ClassNotFoundException is a runtime exception that is thrown when an application tries to load a class at runtime using the Class.forName() or loadClass() or findSystemClass() methods ,and the class with specified name are not found in the classpath. For example, you may have come across this exception when you try to connect to MySQL or Oracle databases and you have not updated the classpath with required JAR files. Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For example, the below program will throw ClassNotFoundException if the mentioned class "oracle.jdbc.driver.OracleDriver" is not found in the classpath.
public class CustomClassNotFoundException

{

    public static void main(String[] args)

    {

        try

        {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        }catch (ClassNotFoundException e)

        {

            e.printStackTrace();

        }

    }

}

If you run the above program without updating the classpath with required JAR files, you will get an exception like:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Unknown Source)

at pack1.CustomClassNotFoundException.main(CustomClassNotFoundException.java:17)

NoClassDefFoundError 

NoClassDefFoundError is an error that is thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime. For example, compile the program below.
class A

{

  // some code

}

public class B

{

    public static void main(String[] args)

    {

        A a = new A();

    }

}

When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: A

at A.main(A.java:10)

Caused by: java.lang.ClassNotFoundException: A

at java.net.URLClassLoader.findClass(URLClassLoader.java:381)

at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)

at java.lang.ClassLoader.loadClass(ClassLoader.java:357)


Recap

ClassNotFoundException
NoClassDefFoundError
It is an exception. It is of type java.lang.Exception.
It is an error. It is of type java.lang.Error.
It occurs when an application tries to load a class at run time which is not updated in the classpath.
It occurs when java runtime system doesn't find a class definition, which is present at compile time, but missing at run time.
It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass().
It is thrown by the Java Runtime System.
It occurs when classpath is not updated with required JAR files.
It occurs when required class definition is missing at runtime.

Steps to Design Hibernate Application

Steps to Design Hibernate Application
1. Design POJO class (Greet.java) Prepare a POJO class with setter and getter methods.
package com.becbe.hibernate.ch1;
public class Greet {

      private long id;

      private String greetmsg;

      public Greet(){}

      public long getId() {

            return id;

      }

      public void setId(long id) {

            this.id = id;

      }

      public String getGreetmsg() {

            return greetmsg;

      }

      public void setGreetmsg(String greetmsg) {

            this.greetmsg = greetmsg;

      }



}
2. Write mapping file (Greet.hbm.xml)







      

            

                  

            

            
    

      

3. Write Configuration file (hibernate.cfg.xml)













com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/mysql

root

root

org.hibernate.dialect.MySQLDialect

true

create








4. To design a Testclass (TestGreet.java)
1. Create a Configuration Object. 2. Create a SessionFactory Object by using buildSessionFactory() from Configuration Object. 3. Create a Session Object by using SessionFactory Object openSession() method. 4. Get Transaction object by using beginTransaction() from Session object.
package com.becbe.hibernate.ch1;

import java.util.ArrayList;

import java.util.List;



import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.hibernate.classic.Session;



public class TestGreet {

   

      public static void display(Greet g)

      {

            System.out.println("List Of MSG in GREET Table");

      System.out.println(g.getGreetmsg());

   

      }



      /**

       * @param args

       */

      public static void main(String[] args) {

      SessionFactory sf=new Configuration().configure().buildSessionFactory();

      Session s=sf.openSession();

      Transaction tx=s.beginTransaction();

      Greet g=new Greet();

      g.setGreetmsg("hi sree h ru");

      s.save(g);

      tx.commit();

      s.close();

      Session s1=sf.openSession();

      Greet g1=(Greet)s1.load(Greet.class,2L);

      TestGreet.display(g1);

      s1.close();

   

      }



}

Example: How insert records in to Database using JDBC API

Example: How insert records in to Database using JDBC API

The following example describes how to insert records into Employee table in MySQL using JDBC API.


SOURCE:InsertDB.java
OUTPUT:
Enter value for Emp Id : 
14234
Enter value for Emp Name : 
jack merlin
record inserted successfully
Do you want to continue to insert : (yes/no)

How to connect MS Access data base using JDBC in JSP

In this post we are going to discuss about , how to connect MS Access using JDBC in JSP.
SOURCE : msaccessconnection.jsp
Manigandan K Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot. - Manigandan K
Follow Me @Google+

How to create table in Database using JDBC API

How to create table in Database using JDBC API
In this article , we are going to learn about, how to create table in Database using statement interface.

To execute the following program, we required mysql-connector-java-5.1.26-bin.jar file, in classpath. click here to download.


Source:CreateTableInDB.java

OUTPUT
Employee table created successfully

Connection Interface

Connection Interface

A Connection enables the session between java application and database. The Connection interface has Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(),rollback() etc. By default, any changes after executing query is commits connection automatically.


Useful methods in java.sql.Connection interface:
public Statement createStatement() It creates a statement object that can be used to execute SQL queries.
public Statement createStatement(int resultSetType,int resultSetConcurrency) It creates a Statement object that will generate ResultSet objects with the given type and concurrency.
public void setAutoCommit(boolean status)It is used to set the commit status.By default it is true.
public void commit() It saves the changes made since the previous commit/rollback permanent.
public void rollback() It is used to drop all changes made since the previous commit/rollback.
public void close() It is used close the connection and Releases a JDBC resources immediately.

Example: Connection Interface
SOURCE:TestDBConnection.java

OUTPUT
Connected Data base successfully ..!

Top 7 Java 8 Books

Top 7  Java 8 Books
Java 8 is the most significant release of Java SE in recent years. Its brand-new features and functional style of programming can change the way programmers write Java code fundamentally. Java 8 focuses on the following primarily new features:
  • Lambda Expressions.
  • The Streams API and parallel data processing.
  • New changes to Interfaces and multiple inheritances.
  • The new Date and Time API.
  • The Nashorn Javascript Engine

1. Java SE 8 for the Really Impatient

Java SE 8 ImpatientAuthor: Cay S. Horstmann
Publisher: Addison-Wesley Professional
Published Date: January 24, 2014
Paperback: 240 pages
Read Full Customer Reviews
Content Coverage:
  • Lambdas Expressions
  • The Stream API
  • Programming with Lambdas
  • JavaFX
  • The New Date and Time API
  • Concurrency Enhancements
  • The Nashorn Javascript Engine
  • Miscellaneous Goodies
  • Java 7 Features that You May Have Missed




More information about Java SE 8 for the Really Impatient on Amazon


2. Java 8: The Fundamentals [Kindle Edition]

Java 8 FundamentalsAuthor: Dane Cameron
Publisher: Cisdal Publishing
Published Date: March 15, 2014
File Size: 2247 KB
Read Full Customer Reviews
Content Coverage:
  • Lambda Expressions
  • Streams API
  • Interfaces
  • Java Date and Time API
  • Nashorn








More information about Java 8: The Fundamentals on Amazon


3. Java 8 Lambdas: Pragmatic Functional Programming

Java 8 LambdasAuthor: Richard Warburton
Publisher: O'Reilly Media
Published Date: April 7, 2014
Paperback: 182 pages
Read Full Customer Reviews
Content Coverage:
  • Lambda Expressions
  • Streams
  • Libraries
  • Enhanced Collections and Collectors
  • Data Parallelism
  • Testing, Debugging and Refactoring
  • Design and Architectural Principles
  • Lambda-Enabled Concurrency



More information about Java 8 Lambdas: Pragmatic Functional Programming on Amazon

4. Java 8 Pocket Guide

Java 8 PocketAuthor: Robert Liguori and Patricia Liguori
Publisher: O'Reilly Media
Published Date: April 28, 2014
Paperback: 242 pages
Read Full Customer Reviews
Content Coverage:
  • Part I: Language
    • Naming Conventions
    • Lexical Elements
    • Fundamental Types
    • Reference Types
    • Object-Oriented Programming
    • Statements and Blocks
    • Exception Handling
    • Java Modifiers
  • Part II: Platform
    • Java Platform, Standard Edition
    • Development Basics
    • Memory Management
    • Basic Input and Output
    • New I/O API (NIO.2)
    • Concurrency
    • Java Collections Framework
    • Generics Framework
    • The Java Scripting Framework API
    • Date and Time API
    • Lambda Expressions
  • Part III: Appendixes
    • Fluent APIs
    • Third-Party Tools
    • UML Basics
More information Java 8 Pocket Guide on Amazon


5. Java SE 8 for Programmers

Java SE 8 ProgrammersAuthor: Paul Deitel and Harvey Deitel
Publisher: Prentice Hall
Published Date: April 9, 2014
Paperback: 1104 pages
Read Full Customer Reviews
Content Coverage:
  • Introduction to Java and Test-driving a Java Application
  • Introduction to Java Applications; Input/Output and Operators
  • Introduction to Classes, Objects, Methods and Strings
  • Control Statements: Part 1; Assignment, ++ and -- Operators
  • Control Statements: Part 2; Logical Operators
  • Methods: A Deeper Look
  • Arrays and ArrayLists
  • Classes and Objects: A Deeper Look
  • Object-Oriented Programming: Inheritance
  • Object-Oriented Programming: Polymorphism and Interfaces
  • Exception Handling: A Deeper Look
  • Swing GUI Components: Part 1
  • Graphics and Java 2D
  • Strings, Characters and Regular Expressions
  • Files, Streams and Object Serialization
  • Generic Collections
  • Java SE 8 Lambdas and Streams
  • Generic Classes and Methods
  • Swing GUI Components: Part 2
  • Concurrency
  • Accessing Databases with JDBC
  • JavaFX GUI
  • ATM Case Study, Part 1: Object-Oriented Design with the UML
  • ATM Case Study, Part 2: Implementing an Object-Oriented Design
More information about Java SE 8 for Programmers on Amazon


6. Java 8 New Features: A Practical Heads-Up Guide

Java 8 New FeaturesAuthor: Richard Reese
Publisher: P8tech
Published Date: May 15, 2014
Paperback: 443 pages
File Size (Kindle Edition): 4522 KB
Read Full Customer Reviews
Content Coverage:
  • Chapter 1: Java 8 and Interface Enhancements
  • Chapter 2: Lambda Expressions
  • Chapter 3: Streams
  • Chapter 4: Date and Time
  • Chapter 5: Odds and Ends
  • Appendix: Date and Time Classes
More information about Java 8 New Features on Amazon


7. Java 8 in Action

Java 8 in ActionAuthor: Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft
Publisher: Manning Publications
Published Date: August 28th, 2014
Paperback: 424 pages
Read Full Customer Reviews
Content Coverage:
  • Part I: Fundamentals
    • Java 8: why should you care?
    • Passing code with behavior parameterization
    • Lambda Expressions
  • Part II: Functional-Style Data Processing
    • Processing Data with Streams
    • Collecting Data with Streams
    • Parallel Data Processing and Performance
  • Part III: Effective Java 8 Programming
    • Refactoring, Testing, Debugging
    • Default Methods
    • Optional: A Better Alternative to Null
    • CompletableFuture: composable asynchronous programming
    • New Date and Time API
  • Part IV: Beyond Java 8
    • Thinking Functionally
    • Functional Programming Technique
    • Blending OOP and FP: comparing Java 8 and Scala
    • Conclusions and “where next” for Java

Hibernate Framework

Hibernate Framework

Hibernate Framework

Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool.
It act as a bridge between Objects and relational data base. Hibernate maps objects with relation.An ORM tool simplifies the data creation, data manipulation and data access.
It is a programming technique that maps the object to the data stored in the database.
hibernate tutorial, An introduction to hibernate
The ORM tool internally uses the JDBC API to interact with the database.

JSF Interview Questions - home

JSF Interview Questions - home
Q: What is JavaServer Faces?
A: JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways:

• Makes it easy to construct a UI from a set of reusable UI components
• Simplifies migration of application data to and from the UI
• Helps manage UI state across server requests
• Provides a simple model for wiring client-generated events to server-side application code
• Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

Q: How to pass a parameter to the JSF application using the URL string?
A: if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");
From the page, you can access the same parameter using the predefined variable with name param. For example,
<h:outputText value="#{param['id']}" />
Note: You have to call the jsf page directly and using the servlet mapping.

Q: How to add context path to URL for outputLink?
A: Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:
<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">
Q: How to get current page URL from backing bean?
A: You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

Q: How to access web.xml init parameters from java code?
You can get it using externalContext getInitParameter method. For example, if you have:
<context-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>
You can access this connection string with:
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

Q: How to access web.xml init parameters from jsp page?
You can get it using initParam pre-defined JSF EL valiable.
For example, if you have:
<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>
You can access this parameter with #{initParam['productId']} . For example:
Product Id: <h:outputText value="#{initParam['productId']}"/>