Tuesday, August 14, 2012

struts

1. Introduction

    "Read the directions and directly you will be directed in the right direction."

The framework documentation is written for active web developers and assumes a working knowledge about how Java web applications are built. For more about the underlying nuts and bolts, see the Key Technologies Primer.

1.1 Forward into the Past! (or a brief history of Struts)

When Java servlets were first invented, many programmers quickly realized that they were a Good Thing. They were faster and more powerful that standard CGI, portable, and infinitely extensible.

But writing HTML to send to the browser in endless println() statements was tiresome and problematic. The answer to that was JavaServer Pages, which turned Servlet writing inside-out. Now developers could easily mix HTML with Java code, and have all the advantages of servlets. The sky was the limit!

Java web applications quickly became "JSP-centric". This in-and-of itself was not a Bad Thing, but it did little to resolve flow control issues and other problems endemic to web applications.

Clearly, another paradigm was needed ...

Many clever developers realized that JavaServer Pages AND servlets could be used together to deploy web applications. The servlets could help with the control-flow, and the JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets together became known as Model 2 (meaning, presumably, that using JSPs alone was Model 1).

Of course, there is nothing new under the Sun ... and many have been quick to point out that JSP's Model 2 follows the classic Model-View-Controller design pattern abstracted from the venerable Smalltalk MVC framework. Java Web developers now tend to use the terms Model 2 and MVC interchangeably. In this guide, we use the MVC paradigm to describe the framework architecture, which might be best termed a Model 2/MVC design.

The Apache Struts Project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC framework to the Java community. In July 2001, version 1.0 was released, and IOHO, Java Model 2 development has never been quite the same.

1.2 The Model-View-Controller ('MVC') Design Pattern

The term "MVC" originated with the SmallTalk Model-View-Controller framework. Under MVC, an application is seen as having three distinct parts. The problem domain is represented by the Model. The output to the user is represented by the View. And, the input from the user is represented by Controller.

1.2.1 The Model: System State and Business Logic JavaBeans

The Model portion of an MVC-based system can be often be divided into two major subsystems -- the internal state of the system and the actions that can be taken to change that state.

In grammatical terms, we might think about state information as nouns (things) and actions as verbs (changes to the state of those things).

Many applications represent the internal state of the system as a set of one or more JavaBeans. The bean properties represent the details of the system' state. Depending on your application's complexity, these beans may be self contained (and know how to persist their own state), or they may be facades that know how to retrieve the system's state from another component. This component may be a database, a search engine, an Entity Enterprise JavaBean, a LDAP server, or something else entirely.

Large-scale applications will often represent the set of possible business operations as methods that can be called on the bean or beans maintaining the state information. For example, you might have a shopping cart bean, stored in session scope for each current user, with properties that represent the current set of items that the user has decided to purchase. This bean might also have a checkOut() method that authorizes the user's credit card and sends the order to the warehouse to be picked and shipped. Other systems will represent the available operations separately, perhaps as Session Enterprise JavaBeans (Session EJBs).

In a smaller scale application, on the other hand, the available operations might be embedded within the Action classes that are part of the framework control layer. This can be useful when the logic is very simple or where reuse of the business logic in other environments is not contemplated.

The framework architecture is flexible enough to support most any approach to accessing the Model, but we strongly recommend that you separate the business logic ("how it's done") from the role that Action classes play ("what to do"). 'nuff said.

For more about adapting your application's Model to the framework, see the Building Model Components chapter.

1.2.2 The View: JSP Pages and Presentation Components

The View portion of a Struts-based application is most often constructed using JavaServer Pages (JSP) technology. JSP pages can contain static HTML (or XML) text called "template text", plus the ability to insert dynamic content based on the interpretation (at page request time) of special action tags. The JSP environment includes a set of standard action tags, such as whose purpose is described in the JavaServer Pages Specification. In addition to the built-in actions, there is a standard facility to define your own tags, which are organized into "custom tag libraries."

The framework includes a set of custom tag libraries that facilitate creating user interfaces that are fully internationalized and interact gracefully with ActionForm beans. ActionForms capture and validate whatever input is required by the application.

For more about the Struts taglibs and using presentation pages with the framework, see the Building View Components section. Additional documentation regarding the taglibs is also available in the Taglibs subproject.

1.2.3 The Controller: ActionServlet and ActionMapping

Struts provides the Controller portion of the application. The Controller is focused on receiving requests from the client (typically a user running a web browser), deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings. An ActionMapping defines a path that is matched against the request URI of the incoming request and usually specifies the fully qualified class name of an Action class. All Actions are subclassed from [org.apache.struts.action.Action]. Actions encapsulate calls to business logic classes, interpret the outcome, and ultimately dispatch control to the appropriate View component to create the response. While the framework dispatches to a View, actually rendering the View is outside its scope.

The framework also supports the ability to use ActionMapping classes that have additional properties beyond the standard ones required to operate the controller. This allows you to store additional information specific to your application and still utilize the remaining features of the framework. In addition, the framework lets you define logical "names" to which control should be forwarded so that an action method can ask for the "Main Menu" page (for example), without knowing the location of the corresponding JSP page. These features greatly assist you in separating the control logic (what to do) with the view logic (how it's rendered).

For more about the control layer, see the Building Controller Components chapter.

1.3 Framework Control Flow

The framework provides several components that make up the Control layer of a MVC-style application. These include a controller component (servlet), developer-defined request handlers, and several supporting objects.

The Struts Taglib component provides direct support for the View layer of a MVC application. Some of these tags access the control-layer objects. Others are generic tags found convenient when writing applications. Other taglibs, including JSTL, can also be used with the framework. Other presentation technologies, like Velocity Templates and XSLT can also be used with the framework.

The Model layer in a MVC application is often project-specific. The framework is designed to make it easy to access the business-end of your application, but leaves that part of the programming to other products, like JDBC, Enterprise Java Beans,Object Relational Bridge, or iBATIS, to name a few.

Let's step through how this all fits together.

When initialized, the controller parses a configuration file (struts-config.xml) and uses it to deploy other control layer objects. Together, these objects form the Struts Configuration. The Configuration defines (among other things) the collection of ActionMappings[org.apache.struts.action.ActionMappings] for an application.

The controller component consults the ActionMappings as it routes HTTP requests to other components in the framework. Requests may be forwarded to JavaServer Pages or Action[org.apache.struts.action.Action] subclasses provided by the application developer. Often, a request is first forwarded to an Action and then to a JSP (or other presentation page). The mappings help the controller turn HTTP requests into application actions.

An individual ActionMapping[org.apache.struts.action.ActionMapping] will usually contain a number of properties including:

    a request path (or "URI"),
    the object type (Action subclass) to act upon the request, and
    other properties as needed.

The Action object can handle the request and respond to the client (usually a Web browser) or indicate that control should be forwarded elsewhere. For example, if a login succeeds, a login action may wish to forward the request onto the mainMenu page.

Action objects have access to the application's controller component, and so have access to that members's methods. When forwarding control, an Action object can indirectly forward one or more shared objects, including JavaBeans, by placing them in one of the standard contexts shared by Java Servlets.

For example, an Action object can create a shopping cart bean, add an item to the cart, place the bean in the session context, and then forward control to another mapping. That mapping may use a JavaServer Page to display the contents of the user's cart. Since each client has their own session, they will each also have their own shopping cart.

Most of the business logic in an application can be represented using JavaBeans. An Action can call the properties of a JavaBean without knowing how it actually works. This encapsulates the business logic, so that the Action can focus on error handling and where to forward control.

JavaBeans can also be used to manage input forms. A key problem in designing Web applications is retaining and validating what a user has entered between requests. You can define your own set of input bean classes, by subclassing ActionForm[org.apache.struts.action.ActionForm]. The ActionForm class makes it easy to store and validate the data for your application's input forms. The ActionForm bean is automatically saved in one of the standard, shared context collections, so that it can be used by other objects, like an Action object or another JSP.

The form bean can be used by a JSP to collect data from the user ... by an Action object to validate the user-entered data ... and then by the JSP again to re-populate the form fields. In the case of validation errors, the framework has a shared mechanism for raising and displaying error messages.

Another element of the Configuration are the ActionFormBeans[org.apache.struts.action.ActionFormBeans]. This is a collection of descriptor objects that are used to create instances of the ActionForm objects at runtime. When a mapping needs an ActionForm, the servlet looks up the form-bean descriptor by name and uses it to create an ActionForm instance of the specified type.

Here is the sequence of events that occur when a request calls for an mapping that uses an ActionForm:

    The controller servlet either retrieves or creates the ActionForm bean instance.
    The controller servlet passes the bean to the Action object.
    If the request is being used to submit an input page, the Action object can examine the data. If necessary, the data can be sent back to the input form along with a list of messages to display on the page. Otherwise the data can be passed along to the business tier.
    If the request is being used to create an input page, the Action object can populate the bean with any data that the input page might need.

The Struts Taglib component provides custom tags that can automatically populate fields from a JavaBean. All most JavaServer Pages really need to know is the field names to use and where to submit the form.

Other tags can automatically output messages queued by an Action or ActionForm and simply need to be integrated into the page's markup. The messages are designed for localization and will render the best available message for a user's locale.

The framework and Struts Taglib were designed from the ground-up to support the internationalization features built into the Java platform. All the field labels and messages can be retrieved from a message resource. To provide messages for another language, simply add another file to the resource bundle.

Internationalism aside, other benefits to the message resources approach are consistent labeling between forms, and the ability to review all labels and messages from a central location.

For the simplest applications, an Action object may sometimes handle the business logic associated with a request. However, in most cases, an Action object should invoke another object, usually a JavaBean, to perform the actual business logic. This lets the Action focus on error handling and control flow, rather than business logic. To allow reuse on other platforms, business-logic JavaBeans should not refer to any Web application objects. The Action object should translate needed details from the HTTP request and pass those along to the business-logic beans as regular Java variables.

In a database application, for example:

    A business-logic bean will connect to and query the database,
    The business-logic bean returns the result to the Action,
    The Action stores the result in a form bean in the request,
    The JavaServer Page displays the result in a HTML form.

Hibernate


Hibernate (Java)


Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

Hibernate is free software that is distributed under the GNU Lesser General Public License.

Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It also generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases with little performance overhead.



Mapping
Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotations are used. Hibernate can use the XML file or the annotations to maintain the database schema.

Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

Hibernate supports the mapping of custom value types. This makes the following scenarios possible:

    Overriding the default SQL type that Hibernate chooses when mapping a column to a property.
    Mapping Java Enum to columns as if they were regular properties.
    Mapping a single property to multiple columns.


Persistence

Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.[1]

Collections of data objects are typically stored in Java collection objects such as Set and List. Java generics, introduced in Java 5, are supported. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3.

Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.

Hibernate Query Language (HQL)

Hibernate provides an SQL inspired language called Hibernate Query Language (HQL) which allows SQL-like queries to be written against Hibernate's data objects. Criteria Queries are provided as an object-oriented alternative to HQL.
Integration

Hibernate can be used both in standalone Java applications and in Java EE applications using servlets, EJB session beans, and JBI service components. It can also be included as a feature in other programming languages. For example, Adobe integrated Hibernate into version 9 of ColdFusion (which runs on J2EE app servers) with an abstraction layer of new functions and syntax added into CFML.
Entities and components

In Hibernate jargon, an entity is a stand-alone object in Hibernate's persistent mechanism which can be manipulated independently of other objects. In contrast, a component is subordinate to other entities and can be manipulated only with respect to other entities. For example, an Album object may represent an entity but the Tracks object associated with the Album objects would represent a component of the Album entity if it is assumed that Tracks can only be saved or retrieved from the database through the Album object. Unlike J2EE, it can switch databases.
History

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.

Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.

JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate.

In 2010, Hibernate version 3.x was released with the features like: a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 Annotations (Java's metadata feature). As of 2010 Hibernate 3 (version 3.5.0 and up) was a certified implementation of the Java Persistence API 2.0 specification via a wrapper for the Core module which provides conformity with the JSR 317 standard.[2]

In Dec 2011, Hibernate Core 4.0.0 Final was released. This includes new features like: Initial multi-tenancy support, Introduction of ServiceRegistry (which is a major change in how Hibernate builds and manages "services"), Clean up of Session opening from SessionFactory, Improved integration via org.hibernate.integrator.spi.Integrator and auto discovery, Improved logging with i18n support and message codes, Initial work on more clear split between API, SPI and implementation classes, Clean up of deprecated methods, classes, etc.[3]

In 2012, Hibernate 5 started development. It will contain JPA 2.1 support.
Application programming interface

The Hibernate API is provided in the Java package org.hibernate.
org.hibernate.SessionFactory interface

References immutable and threadsafe object creating new Hibernate sessions. Hibernate-based applications are usually designed to make use only of a single instance of the class implementing this interface (often exposed using a singleton design pattern).
org.hibernate.Session interface

Represents a Hibernate session i.e. the main point of the manipulation performed on the database entities. The latter activities include (among the other things) managing the persistence state (transient, persisted, detached[clarification needed]) of the objects, fetching the persisted ones from the database and the management of the transaction demarcation[clarification needed].

A session is intended to last as long as the logical transaction on the database. Due to the latter feature, Session implementations are not expected to be threadsafe nor to be used by multiple clients.
Software components

The Hibernate software includes the following components:[4]


    Hibernate ORM (was known as Hibernate Core before release 4.1[5]) – the base software for an object-relational mapping solution for Java environments[6]
    Hibernate Annotations (merged into Hibernate Core/ORM since version 3.6[7]) – metadata that governs the transformation of data between the object-oriented model and the relational database model according to the JSR 317 Java Persistence API (JPA 2)[8]
    Hibernate EntityManager – together with Hibernate Annotations, a wrapper that implements a JSR 317 Java Persistence API (JPA 2) persistence solution on top of Hibernate Core[9]
    Hibernate Envers – auditing and versioning of persistent classes[10]
    Hibernate OGM – Object/Grid Mapper is an extension to store data in a NoSQL store[11]
    Hibernate Shards – horizontal partitioning for multiple relational databases[12]
        NOTE: Hibernate Shards is not compatible with the 4.x versions of Hibernate Core... some of the Shards capability was integrated into Core in the 4.0 release.
    Hibernate Search – integrates the full text library functionality from Apache Lucene in the Hibernate and JPA model[13]
    Hibernate Tools – a set of tools implemented as a suite of Eclipse plugins and Ant tasks included in JBoss Developer Studio[14]
    Hibernate Validator – the reference implementation of JSR 303 Bean Validation[15]
    Hibernate Metamodel Generator – an annotation processor that creates JSR 317 Java Persistence API (JPA 2) static metamodel classes using the JSR 269 Pluggable Annotation Processing API[16]
    NHibernate – an object-relational mapping solution for the .NET Framework[17]

Monday, August 13, 2012

How to connect Java Application with Oracle Database using JDBC Driver



How to connect Java Application with Oracle Database using JDBC Driver -

Today I will go through the basic steps to connect a Java Application with Oracle Database using JDBC Driver (Java Database Connectivity). To develop Enterprise Product connectivity of java application and oracle database is essential. When I was new to java, i have faced some problem for java and database connectivity using jdbc. So I want to make all this process bit easier for all the new comer in java and windows platform.





Prerequisites :

    Microsoft Windows Xp Service Pack 2 or above.
    Java Developement Kit.
    Oracle Database.
    Oracle JDBC Driver.According to your database version.
    One Integrated Development Environment.like Netbeans,Eclipse

Steps for configuring the system and creating DSN (ODBC Data Source):

    1.Install Java Development Kit and Oracle Database.
    2.Place Oracle JDBC Driver (*.jar file) in java runtime folder and java development kit folder . eg: 'C:\Program Files\Java\jre1.6.0\lib\ext' and 'C:\Program Files\Java\jdk1.6.0\jre\lib\ext'.
   3. Create a Data Source Name (DSN) required for database connectivity in windows.
    For DSN go to Start->Control Panel->Administrative Tools->Data Sources (ODBC).
    4.ODBC Data Source Administrator will open. Click on the Add button to create a new data source.
    





5.Select 'Microsoft ODBC for Oracle' & click Next.



 7.Fill the Data Source Name - name for the data source, Description - Just a simple description, User Name - Oracle Database User name, Server - name of the server where database is installed ,( localhost - if it is installed in the local machine or the IP if the the database is installed in a remote machine). Click OK and close the ODBC Data Source Administrator.







Now, the system is configured to run any java oracle connectivity program.You can start coding the program in any IDE or open a notpad.

Below is the source code of a jdbc program to determine wheather all your setting are OK or not. Compile the program and execute it. If the program is executed without any error or exception and you get 'JDBC Driver loaded' and 'Connected to the Oracle Database' as output then you have done all the setting correctly and you are able to connect to the oracle database through your java program.
If you encounter any problem please get back to me, I will help you to sought out the problem.


Source code :

import java.sql.*;

public class ConnectOracle {

public static void main(String[] args) {
String driver="sun.jdbc.odbc.JdbcOdbcDriver"; //
String cs="jdbc:odbc:connectOracle"; //connectOracle is the data source name
String user = "system"; //username of oracle database
String pwd = "tom"; //password of oracle database
Connection con = null; //connection variable assigned to null
try
{
Class.forName(driver);// for loading the jdbc driver
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("JDBC Driver loaded");
try
{
con=DriverManager.getConnection(cs,user,pwd);// for establishing connection with database
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Connected to the Oracle Database");
try
{
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//end of main()
}//end of class()

ODBC Driver for Access 2000, 2002, 2003 and 2007 Databases

The Easysoft ODBC-Access Driver connects 32-bit and 64-bit applications on Linux and Unix to Microsoft Access databases.

To ensure compatibility with databases created in as many versions of Access as possible, the Easysoft ODBC-Access Driver supports both the MDB and ACCDB database formats. The Easysoft ODBC-Access Driver can connect to .mdb databases created in Access 2000–2003 and Office Access 2007. The forthcoming release of Access, Office Access 2010, will continue to support .mdb format databases. The Easysoft ODBC-Access Driver can also connect to .accdb databases, which is the default format for databases created in Office Access 2007 and later. The Easysoft ODBC-Access Driver is a flexible, future-proof solution therefore, which will integrate Linux/Unix with whatever version of Access suits your organisation best.

The Easysoft ODBC-Access Driver provides read-write access to Access databases, so your Linux/Unix applications can update as well as retrieve Access data. If you need to restrict users to read-only access, you can configure the driver to open the database in read-only mode, just as you can with the Access front-end application on Windows.

Choosing the Easysoft ODBC-Access Driver to connect Linux/Unix with Access will not disrupt your existing Access solution’s environment or users. There is no software to install on your Windows machines. You do not need to change where your database file is located. The Easysoft ODBC-Access Driver can open an Access database stored on a Windows share, so there is no need to copy the database file to your Linux/Unix machine. To ensure concurrent access to the database by Windows and Linux/Unix users is problem free, the Easysoft ODBC-Access Driver uses Access’ locking file mechanism. The driver will also prevent its users from opening a database if another user has the database opened for exclusive access, again mirroring the Access front-end’s behaviour for seamless integration.

The Easysoft ODBC-Access Driver supports encrypted/encoded .mdb files, which is an Access security feature that protects Access data from unauthorised viewing. When you use the Easysoft ODBC-Access Driver to load a remote .mdb file, encrypting/encoding the database protects the privacy of the Access data as it is sent across the network.

To ensure compatibility with multiple Linux/Unix applications, the Easysoft ODBC-Access Driver supports the unixODBC driver manager. Most (if not all) Linux/Unix applications support unixODBC, which, as a mature, non-proprietary, robust driver manager, is part of the standard installation of many Linux distributions. To provide a self-contained solution, the Easysoft ODBC-Access Driver distribution itself includes the unixODBC driver manager. To get you going quickly, the Easysoft ODBC-Access Driver automatically installs itself into unixODBC, making the driver immediately available to your applications.
Platforms

The Easysoft ODBC-Access Driver is currently available on these platforms:
Version     Platform     Distribution
v1.0 (Access 2000 - 2007)     AIX (PPC) (32 - Bit)     (4.3-6.1)
v1.0 (Access 2000 - 2007)     AIX (PPC) (64 - Bit)     (5.0-6.1)
v1.0 (Access 2000 - 2007)     HP-UX (Itanium i64) (32 - Bit)     (11i)
v1.0 (Access 2000 - 2007)     HP-UX (Itanium i64) (64 - Bit)     (11i)
v1.0 (Access 2000 - 2007)     HP-UX (PA-Risc) (32 - Bit)     (10.10-11)
v1.0 (Access 2000 - 2007)     HP-UX (PA-Risc 2) (64 - Bit)     (11)
v1.0 (Access 2000 - 2007)     Linux (x86) (32 - Bit)     (kernel 2.2-2.6, glibc 2.1+)
v1.0 (Access 2000 - 2007)     Linux (x86) (64 - Bit)     (kernel 2.6, glibc 2.3.5)
v1.0 (Access 2000 - 2007)     Solaris (Sparc) (32 - Bit)     (2.6-2.10)
v1.0 (Access 2000 - 2007)     Solaris (Sparc) (64 - Bit)     (2.8-2.10)
v1.0 (Access 2000 - 2007)     Solaris (x86) (32 - Bit)     (2.8)
v1.0 (Access 2000 - 2007)     Solaris (x86) (64 - Bit)     (2.8)

If the Access ODBC driver is not available for your platform, we have an alternative Access solution, which is available for additional Unix platforms.

Download Access ODBC driver.
MSAccess Linux ODBC Driver

Connects to MS Access databases (.mdb or .accdb) from 32-bit and 64-bit Linux platforms such as CentOS, Debian GNU/Linux, Fedora, Kubuntu/Ubuntu (Edgy Eft/Feisty Fawn/Gutsy Gibbon/Hardy Heron/Intrepid Ibex/Jaunty Jackalope/Karmic Koala), Mandrake/Mandriva, OpenSUSE/SUSE, Red Hat, Slackware and more.
MSAccess Unix ODBC Driver

Connects to MS Access databases (.mdb or .accdb) from 32-bit and 64-bit IBM AIX, HP-UX and Sun Solaris platforms.

MS Access JDBC Driver -- Connecting MS Access with Java



To connect Java with MS Access, you need a JDBC driver. Although Microsoft do not produce a JDBC driver for MS Access, Easysoft provide two Microsoft Access JDBC drivers. Use these JDBC drivers to provide the connectivity layer between your Java code and MS Access database.

    Download Type 2 MS Access JDBC driver for Windows

    The Easysoft JDBC-Access Gateway connects Java running on Windows to local MS Access databases. For more information, see the JDBC-Access Gateway Getting Started Guide.
    Download Type 3 MS Access JDBC driver for Linux and Unix

    The JDBC-ODBC Bridge connects Java running on Linux or Unix to remote MS Access databases. For more information, see this tutorial.

Accessing MS Access from Java

This tutorial shows how to access MS Access databases from Java.

Java -> JOB Client -> TCP/IP -> JOB Server -> Microsoft Driver Manager -> Microsoft Access ODBC Driver -> Microsoft Access
Contents

    Prerequisites
    Assumptions
    Configuring the Microsoft Access ODBC Data Source
    Running the Demo Applet
    Running the Demo Application
    Common Problems

Prerequisites

    An installed and licensed Easysoft JDBC-ODBC Bridge (JOB) server on a supported Windows platform that has Microsoft Office installed.

    If you have not yet installed the JOB software or you are having problems with the installation, use our Getting Started Guide to help you through the installation.
    An existing Access database file (.mdb) on the Windows machine.

Assumptions

    You accepted the default options during the install.
    This tutorial was written assuming the demonstration clients were installed on the same Windows machine as the JOB server.

    You can check to see if you have these installed by choosing Start > Programs > Easysoft > JDBC-ODBC Bridge.

    From here you should see both an Applet demo and an Application demo.
    We have also assumed that you have installed the JOB software as a valid Windows User who has access to the target database.

Configuring the Microsoft Access ODBC Data Source

You will find the ODBC Administrator within Administrative Tools from your Control Panel.

ODBC Data Source Administrator System DSN tab.

From here you will create your new System DSN. Click the Add button and then select the Microsoft Access Driver and click Finish.

ODBC Microsoft Access Setup dialog box.

Give your DSN a meaningful name and click Select. Here you will be able to browse to your existing .mdb file.

Once you have selected the database you want to access, click OK and then OK again to exit the dialog box. You have now created your data source.
Running the Demo Applet

Within your services manager, make sure that the JOB service is running, and then open a web browser and go to the following URL http://localhost:8031.

This will open the JOB Web Administrator where you have many configuration options. On the left hand side, you will see a Test Applet link. This will show you a box with various parameters. The Logon User and Password should be the same as your valid Windows details.

Once you have entered your username and password, click the Connect button. This will then display a pop-up box:

Easysoft JDBC-ODBC Bridge Browse Connect dialog box.

As you can see from the image, we have created a system DSN that points to northwind.mdb called NORTHWIND. (There is a Northwind database included in most versions of Microsoft Office.) If you have more than one system DSN, your newly created DSN will appear at the bottom of the drop down list.

From here, simply select the DSN you wish to connect to and click Connect. (You will not need to add a database username and password as the Access database will use NT authentication.)

Once connected, you will see a list of tables. You can issue a simple select * from table by double clicking the table you wish to query. Alternatively, you can issue your own SQL in the SQL field.

This will return the result set in an applet window:

Result set displayed in an applet window.

Download Windows JDBC Driver for MS Access. Free Trial. Download UNIX JDBC Driver for MS Access. Free Trial.
Running the Demo Application

To run the Demo Application, choose Start > Programs > Easysoft > JDBC-ODBC Bridge > AWT Application Demo.

This should now display the demo application:

Easysoft JDBC-ODBC Bridge demo application.

You can see that the connection URL already has the first part of the connection string in it -- jdbc:easysoft:

The complete connection string should take the form of:

 jdbc:easysoft://servername/datasource:logonuser=username:logonpassword=password

From here, you do not need to add any further details. Simply click Connect.

From here, you will be able to see a list of tables from your Access database. The same applies to the SQL commands as it does in the Demo Applet section. Simply issue your SQL command and click Submit.
Common Problems
Why can’t I connect to my Microsoft Access .mdb file using the Easysoft JDBC-ODBC Bridge?

The problem is likely to be that the Microsoft Access .mdb file is on a mapped network drive that can only be accessed by a named user.

There are three possible solutions:

    Move the .mdb file to a drive that can be accessed by a service.
    Run the JOB service as the user who has access to the drive/file.
    Add the following attributes to the JDBC connection URL:

    logonuser=username:logonpassword:password

Why do I get error "[JOB] Connection failed[JOB] RPC Exception: access denied (java.net.SocketPermission ip address/server name:8031 connect,resolve)" when trying to connect in the test applet using a fully qualified JDBC URL?

If you have run the test applet from the Start menu, the browser will default to 127.0.0.1 (localhost). This will then be the only IP address/server name you will be able to use in your JDBC URL. You will not be able to use the server’s actual IP address/server name unless you have used either of them in your initial browser address (http://ip address/server name:8031).
Why do I get error "RPC Exception: access denied java.net.SocketPermission" in the JOB applet?

Check that your JDBC connection URL is connecting to the same machine as your browser. For example, http://127.0.0.1:8031 is not the same as the machine name / IP address, so in your connection URL it must match:

 jdbc:easysoft://servername/datasource:logonuser=username:logonpassword=password

Why do I get the error "Client denied access due to access control rule"?

The machine you are running the JOB JDBC driver on has attempted to connect to the specified server (where the JOB Server is running) but there is an access control rule on the server that denies your client access. You need to use the JOB web administration interface to examine the access control rules. Point a web browser at:

http://myserver:8031

Then select Security. The access control rules are defined on this page.

JDBC-Access Gateway


How to connect to Microsoft Access or Microsoft Excel from Java.



Introduction



JDBC is a Java application programming interface (API) that connects Java to relational databases (and other tabular data, such as spreadsheets and flat files). To interact with a database, a Java application uses a JDBC driver. A JDBC driver implements the JDBC API for a particular database.

Microsoft do not produce a JDBC driver for Jet, the underlying database engine for the Microsoft Office product suite. However, Microsoft do produce a Jet-based ODBC driver. (ODBC is another data access technology, the Microsoft implementation of which is included with Windows.) To provide a JDBC interface to Office applications via this native Microsoft interface, a JDBC driver must be able to convert JDBC calls to ODBC calls. As far as the Java application is concerned, it is using a normal JDBC driver. As far as the Office application is concerned, it is being accessed via the normal ODBC driver.

The Easysoft JDBC-Access Gateway is a JDBC driver for Access that uses the Java Native Interface (JNI) to communicate with the Access ODBC driver library. Because this ODBC driver library also supports Excel, the Easysoft JDBC-Access Gateway also provides JDBC access to Excel.

You can use the Easysoft JDBC-Access Gateway to connect Java applications, servlet/JavaServer Pages (JSP) engines, integrated development environments (IDE) and application servers with Access and Excel.

The Easysoft JDBC-Access Gateway has both a Java component and a native Windows component, which is used to communicate with the Microsoft ODBC driver. By default, Java applets cannot load native code libraries; the Java security mechanism prevents this because it cannot police what happens at native code level. To use the Easysoft JDBC-Access Gateway with a Java applet, your Java security policy needs to allow the applet to load native libraries. For example:


/* Sample user .java.policy file */
grant codeBase "http://my_webserver/my_jdbc_applet_dir/-" {
  permission java.lang.RuntimePermission "loadLibrary.*";
};

Note that using applets with the Easysoft JDBC-Access Gateway is not the only way to publish your Access or Excel data on the Web or manipulate the data from within a Web browser. As mentioned, the Easysoft JDBC-Access Gateway is compatible with servlet/JSP engines (such as Apache Tomcat) and application servers (such as Adobe ColdFusion), and these products allow Web-based applications with database backends to be created.
Supported Microsoft File Formats

The native library for the Easysoft JDBC-Access Gateway is odbcjt32.dll, which is Microsoft’s ODBC driver for Access and Excel (also known as the Microsoft ODBC Desktop Database Drivers).

odbcjt32.dll supports the following Access database file formats:

    Version 4.0 .mdb files, which is the default format for databases created in Access 2000, 2002 and 2003.
    Version 3.0 .mdb files, which is the default format for databases created in Access 95 and Access 97.
    Version 2.0 .mdb files, which is the default format for databases created in Access 2.0.

Although Office Access 2007 introduced a new database file format (.accdb), version 4.0 .mdb files continue to be supp
orted by Access 2007 and later.

In addition, odbcjt32.dll supports .xls format workbooks created in:

    Excel 97–2003
    Excel 5.0/95
    Excel 4.0
    Excel 3.0

Although Office Excel 2007 introduced new spreadsheet file formats (.xlsb, .xlsm, .xlsx), .xls files continue to be supported by Excel 2007 and later.
Before You Begin
What You Need To Know

Obtain this information from your system administrator:

    The path to the target Access database (.mdb) or Excel workbook (.xls) on the machine you intend to install the Easysoft JDBC-Access Gateway on.

    The target file must be visible through the local file system on the Easysoft JDBC-Access Gateway machine. For example, in a folder on this machine or a mapped network drive or in a shared folder.

Prerequisite Software
Java Runtime Environment Requirements

You need a Java Runtime Environment (JRE) installed on the Windows machine you want to install the Easysoft JDBC-Access Gateway on. The JRE contains the Java virtual machine (JVM), runtime class libraries, and Java application launcher that are necessary to run programs written in the Java programming language. The Easysoft JDBC-Access Gateway is compatible with JRE 1.6.0 and later.

To check whether you have the JRE installed on your machine and that your JRE version is one the Easysoft JDBC-Access Gateway supports, open a Command Prompt window, and type java -version. For example:

c:\>java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)

If the reported JRE version is 1.5.n or earlier (or you get the error "'java' is not recognized as an internal or external command, operable program or batch file."), you need to obtain a JRE for your machine.

If the output produced by running java -version contains 64-Bit Server VM, you have a 64-bit JRE. The Easysoft JDBC-Access Gateway requires a 32-bit JRE; a 32-bit JRE (x86) will install and function correctly on a 64-bit machine. (The Easysoft JDBC-Access Gateway uses the ODBC Desktop Database Drivers, which is a 32-bit library. There is no 64-bit version of this library. The native component of the Easysoft JDBC-Access Gateway and the JRE must also be 32-bit as you cannot mix 32-bit and 64-bit libraries.)

Windows versions of the JRE are available to download from:

    http://www.oracle.com/technetwork/java/javase/downloads/index.html

Note The Java Development Kit (JDK), which includes the JRE, is also available to download from this web page. However, unless you are going to develop a Java application to run against the Easysoft JDBC-Access Gateway, you only need to download the JRE package.
ODBC Desktop Database Drivers

The ODBC Desktop Database Drivers must be installed on the machine on which you install the Easysoft JDBC-Access Gateway. Note that you do not need to install Access or Excel on the Easysoft JDBC-Access Gateway machine.

Since Windows 2000, the ODBC Desktop Database Drivers (one of the Jet Database Engine Components) have shipped with Windows and so should be already present on your machine as part of the Windows installation.

To check whether the ODBC Desktop Database Drivers are installed, use ODBC Data Source Administrator:

    Do one of the following:
        On 32-bit Windows, in the Windows Run dialog box, type:

        %windir%\system32\odbcad32.exe

        On 64-bit Windows, in the Windows Run dialog box, type:

        %windir%\syswow64\odbcad32.exe

        Note On 64-bit Windows, the ODBC Data Source Administrator that is accessible from Control Panel is a 64-bit application. The 64-bit ODBC Data Source Administrator only lists 64-bit ODBC drivers, and so cannot be used to check whether the ODBC Desktop Database Drivers are installed.
    In ODBC Data Source Administrator, click the Drivers tab.
    In the File column, look for the file name ODBCJT32.DLL.

    If ODBCJT32.DLL is listed, the ODBC Desktop Database Drivers are installed, and you have the prerequisite software for the Easysoft JDBC-Access Gateway. Otherwise, you need to ask your system administrator to install the Microsoft driver before you can use the Easysoft JDBC-Access Gateway.

Installing the Easysoft JDBC-Access Gateway

    Log into the Easysoft website.

    If you have not yet done so, you need to register first. On the registration form, an asterisk (*) indicates that a field is mandatory.
    Download the Easysoft JDBC-Access Gateway distribution.
    Save the distribution file to a temporary directory on the machine where you intend to install the Easysoft JDBC-Access Gateway.
    Execute the file distribution that you downloaded in the previous step.

    Follow the on screen instructions.
    Obtain a free trial licence:
        In Easysoft Data Access License Manager, complete the contact information and click Request License.

        The email contact address you supply must be the email address you registered with on the Easysoft web site.
        Choose Time Limited Trial and click Next.
        Choose Easysoft JDBC-Access Gateway from the drop-down list of products and click Next.
        Click On-Line Request. You will get a message telling you that your license has been added. Click OK.
        Click Finish.

Using the Easysoft JDBC-Access Gateway
Setting the Class Path

The Java class library file for the Easysoft JDBC-Access Gateway is named esmdb.jar. As esmdb.jar is not part of the Java platform, the class path must include the esmdb.jar file. Otherwise, your application will throw a ClassNotFoundException exception when trying to use the Easysoft JDBC-Access Gateway. The class path is a parameter that tells the JVM and Java programs where to find to find third-party and user-defined classes.

esmdb.jar is installed in the following location:

easysoft_installation_folder\Libs

The default location for easysoft_installation_folder is drive:\Program Files\Easysoft Limited\Easysoft JDBC-Access Gateway.

What class path configuration is required depends on your application:
Applications that are Run at the Command Prompt

The CLASSPATH environment variable is used, which can be set on a system, user or session basis. For example, this command sets the class path for Java applications run in a particular command prompt session:

C:\MyJavaApps>set CLASSPATH="%CLASSPATH%;C:\Program Files\Easysoft Limited\Easysoft JDBC-Access Gateway\Libs\esmdb.jar"

Alternatively, you can specify the class path on the Java command line that runs an application by using the java -classpath option.

C:\MyJavaApps> java -cp ".;C:\Program Files\Easysoft Limited\Easysoft JDBC-Access Gateway\Libs\esmdb.jar" MyJavaApp

The following steps show how to set the class path when compiling and running the sample Easysoft JDBC-Access Gateway Java application. (Note that the procedure assumes that you have the JDK installed.)

    Save the sample Java code to a file named ConnectToAccess.java.
    In a Command Prompt, cd to the directory where you saved ConnectToAccess.java.
    Set the class path for the Java compiler and application launcher:

    C:\MyJavaApps>set CLASSPATH="%CLASSPATH%;C:\Program Files\Easysoft Limited\Easysoft JDBC-Access Gateway\Libs\esmdb.jar"
    Compile and run the sample application. For example:

    C:\MyJavaApps> "C:\Program Files\Java\jdk1.6.0_26\bin\javac" ConnectToAccess.java

    C:\MyJavaApps> java ConnectToAccess

    JDBC Driver Information
         Driver name: easysoft.sql.esMdbDriver
         Driver Major Version: 1
         Driver Minor Version: 0
         .
         .
         .

Applications that Run in an IDE

Each IDE has a different method for setting its class path. Setting the CLASSPATH environment variable will not work. You need to add the esmdb.jar folder to the IDE class path.
See Also

    Using the Easysoft JDBC-Access Gateway with Eclipse IDE for Java Developers
    Using the Easysoft JDBC-Access Gateway with NetBeans IDE
    Using the Easysoft JDBC-Access Gateway with Embarcadero JBuilder

Servlets and JSPs

Servlets and JSPs are run in a servlet/JSP engine such as Apache Tomcat. The class path must be set according to the servlet/JSP engine documentation. Setting the CLASSPATH environment variable will not work. You may have to set the engine class path through a GUI or configuration file. Alternatively, you may have to copy esmdb.jar to a particular folder such as lib.
See Also

    Using the Easysoft JDBC-Access Gateway with Apache Tomcat

Connecting to your Access Database or Excel Workbook

The Easysoft JDBC-Access Gateway provides two JDBC drivers: a driver for Access databases and a driver for Excel workbooks.

The Java class for the Access JDBC driver is easysoft.sql.esMdbDriver. The Java class for the Excel JDBC driver is easysoft.sql.esXlsDriver.

To register a Easysoft JDBC-Access Gateway JDBC driver, your Java application must specify the appropriate class. For example:

// Register the Access JDBC driver.
Class.forName("easysoft.sql.esMdbDriver");

–Or–

// Register the Excel JDBC driver.
Class.forName("easysoft.sql.esXlsDriver");

When the relevant JDBC driver is registered, you can establish a connection by using a connection URL and the getConnection method of the DriverManager class. For example:

String connectionUrl = "jdbc:easysoft:mdb" +
   "?DBQ=C:/Users/Public/Northwind.mdb";
Connection con = DriverManager.getConnection(connectionUrl);

To establish a connection with the Easysoft JDBC-Access Gateway, use a connection URL of the form:

jdbc:easysoft:?DBQ=[;=]

where:

    is either mdb for the Access JDBC driver or xls for the Excel JDBC driver.
    is the path to the Access database (.mdb) or Excel workbook (.xls).
    is an Access ODBC driver or an Excel ODBC driver attribute.

Example Connection URLs

Opens an Access database for read-only access:

jdbc:easysoft:mdb?DBQ=C:/Users/Public/Northwind.mdb;ReadOnly=True

Opens an an Access database that is stored in a shared folder:

jdbc:easysoft:mdb?DBQ=//mymachine/myshare/Sales.mdb;

Opens a password-protected Excel workbook from a mapped network drive:

jdbc:easysoft:xls?DBQ=Z:/Orgdata.xls;PWD=p455w0rd

Further Support

    To contact the Easysoft support team, send an email message to support@easysoft.com.

Appendices
Easysoft JDBC-Access Gateway Demonstrators

This sample Java application connects to an Access database and returns a list of tables in the database. The application also prints out information about the database and the Easysoft JDBC-Access Gateway.

import java.sql.*;
import java.util.Properties;

public class ConnectToAccess {

   public static void main(String[] args) {

      // Replace the DBQ value with the path to your Access database.
      String connectionUrl = "jdbc:easysoft:mdb?" +
         "DBQ=C:/Users/Public/Northwind.mdb";

      Driver driver = null;
      DriverPropertyInfo props[] = null;
      Connection con = null;
      DatabaseMetaData dm = null;
      ResultSet rs = null;

      try {
         // Register the Easysoft JDBC-Access Gateway.
         Class.forName("easysoft.sql.esMdbDriver");
         driver = DriverManager.getDriver(connectionUrl);

         System.out.println("JDBC Driver Information");
         System.out.println ("\tDriver name: " +
                     driver.getClass().getName());
         System.out.println("\tDriver Major Version: " +
                 driver.getMajorVersion());
         System.out.println("\tDriver Minor Version: " +
                 driver.getMinorVersion());

         con = DriverManager.getConnection(connectionUrl);

         dm = con.getMetaData();

         System.out.println("\tJDBC Major Version: " +
                 dm.getJDBCMajorVersion());
         System.out.println("\tJDBC Minor Version: " +
                 dm.getJDBCMinorVersion());

         props = driver.getPropertyInfo (connectionUrl, new Properties());

         /* These attributes are Microsoft Access ODBC driver attributes,
            which the Easysoft JDBC-Access Gateway passes to the
            Microsoft driver. Only the DBQ attribute is mandatory. */
         System.out.println ("JDBC URL Attributes");

         for (int i = 0; i < props.length; i++) {
             System.out.print ("\t" + props[i].name);
             System.out.print (" = ");
             System.out.print (props[i].value);
             System.out.print (" : ");
             System.out.println (props[i].description +".");
         }

         System.out.println("Database Information");
         System.out.println("\tDatabase Name: " +
                     dm.getDatabaseProductName());
         System.out.println("\tDatabase Version: " +
                 dm.getDatabaseProductVersion());

         rs = dm.getTables(null, null, "%", null);

         System.out.println("Database Tables");

         // Retrieve type and name for each table in the database.
         while (rs.next()) {
             System.out.println("\t" + rs.getString(3) +
                     " : " + rs.getString(4));
         }
      }

      // Handle any errors that may have occurred.
      catch (Exception e) {
          e.printStackTrace();
      }
      finally {
          if (rs != null) try { rs.close(); } catch(Exception e) {}
          if (con != null) try { con.close(); } catch(Exception e) {}
      }
   }
}

This sample JSP connects to and retrieves data from a JDBC data source that has been configured as a Java Naming and Directory Interface (JNDI) resource named Northwind.


 
   Sample Easysoft JDBC-Access Gateway JSP

 
 
   <%@ page import="javax.naming.*" %>
   <%@ page import="java.sql.*" %>
   <%@ page import="javax.sql.*" %>
   <%@ page import="java.io.PrintWriter" %>

   <%@page contentType="text/html;charset=UTF-8"%>

  

Sample Easysoft JDBC-Access Gateway JSP



   <%

   Connection con = null;
   Statement stmt = null;
   ResultSet rs = null;

   try {

       // Obtain our environment naming context
       Context initCtx = new InitialContext();
       Context envCtx = (Context) initCtx.lookup("java:comp/env");

       // Look up our data source
       DataSource ds = (DataSource) envCtx.lookup("jdbc/Northwind");

       // Allocate and use a connection from the pool
       con = ds.getConnection();

       // Fetch and display data
       stmt = con.createStatement();

       // You need to edit this query
       rs = stmt.executeQuery("SELECT CompanyName FROM suppliers");

       while (rs.next()) {
           // You need to edit this column name
           String s = rs.getString("CompanyName");
           out.print(s + "
");
       }

       rs.close();
       rs = null;
       stmt.close();
       stmt = null;
       con.close(); // Return to connection pool
       con = null;  // Make sure we do not close it twice
   } catch (SQLException e) {
       out.print("Throw e" + e);
   } finally {
     // Always make sure result sets and statements are closed,
     // and the connection is returned to the pool
     if (rs != null) {
       try { rs.close(); } catch (SQLException e) { ; }
       rs = null;
     }
     if (stmt != null) {
       try { stmt.close(); } catch (SQLException e) { ; }
       stmt = null;
     }
     if (con != null) {
       try { con.close(); } catch (SQLException e) { ; }
       con = null;
     }
   }

   %>

 

How to Connect Java to Microsoft Access

Connect Java to Microsoft Access

Easysoft provide two ways to connect Java & MS Access databases:

    The JDBC-Access Gateway, a Type 2 JDBC driver for MS Access. The JDBC-Access Gateway has both a Java component and a native Windows component, which is used to communicate with the Access database file via the MS Access ODBC driver.
    The JDBC-ODBC Bridge, a Type 3 JDBC driver whose client/server architecture allows the Access database file and Java to be on separate machines. The JDBC-ODBC Bridge client is written entirely in Java and does not need any installation — it can be served remotely with a Java applet or copied to a directory where your Java application, servlet/JSP engine, IDE or application server can load JAR files from.

Both the JDBC-Access Gateway and JDBC-ODBC Bridge use the MS Access ODBC driver to access the database file. Using the database vendor’s driver to communicate with the database file may be required to comply with IT company policy at your site.
 



(गेटवे JDBC एक्सेस, टाइप 2 एमएस एक्सेस के लिए JDBC ड्राइवर.JDBC - प्रवेश गेटवे दोनों एक java घटक और एक देशी Windows घटक है, जो ms access  ODBC driver के माध्यम से Access database फ़ाइल के साथ संवाद करने के लिए प्रयोग किया जाता है.
    JDBC ODBC पुल, एक प्रकार 3 JDBC ड्राइवर जिसका क्लाइंट / सर्वर वास्तुकला Access डेटाबेस फ़ाइल और जावा अलग मशीनों पर होना करने के लिए अनुमति देता है. JDBC-ODBC पुल ग्राहक पूरी तरह जावा में लिखा है और किसी भी स्थापना की आवश्यकता नहीं है - यह एक जावा applet के साथ परोसा दूर कर सकते हैं या एक निर्देशिका है, जहां अपने जावा आवेदन, इंजन सर्वलेट JSP / IDE या अनुप्रयोग सर्वर JAR फ़ाइलों को लोड कर सकते हैं नकल से.

दोनों JDBC एक्सेस गेटवे और JDBC ODBC पुल एमएस एक्सेस ODBC ड्राइवर का उपयोग करने के लिए डेटाबेस फ़ाइल का उपयोग. डेटाबेस विक्रेता ड्राइवर का उपयोग करने के लिए डेटाबेस फ़ाइल के साथ संवाद करने के लिए अपनी साइट पर आईटी कंपनी की नीति के साथ अनुपालन की आवश्यकता हो सकती है.)

how can we connect java to mysql database connection

Using JDBC to connect to MySQL from Java Program




This sample Java program connects to MySQL database using JDBC, executes a query and retrieves and prints the value of the database field.

This same sample code can be used to connect to any type of database, all you need to do is change the connection url (dbUrl in the sample). For this code to work properly, you will need to download the mysql driver for JDBC in other words Java Connectors from mysql.com site.

If after downloading the URL it still doesn't work then it is probably due to the classpath. You will have to add the driver jar file in the classpath.
 
(यह नमूना जावा प्रोग्राम MySQL के डेटाबेस JDBC का उपयोग करने के लिए जोड़ता है, एक क्वेरी और retrives के कार्यान्वित और डेटाबेस फ़ील्ड का मूल्य मुद्रित करता है.

यह एक ही नमूना कोड डेटाबेस के किसी भी प्रकार से कनेक्ट करने के लिए इस्तेमाल किया जा सकता है, तुम सब करने की ज़रूरत कनेक्शन यूआरएल (नमूना में dbUrl) बदल रहा है. इस कोड ठीक से काम करने के लिए, आप JDBC के लिए अन्य जावा कनेक्टर्स शब्दों में mysql.com साइट से MySQL चालक डाउनलोड की आवश्यकता होगी.

यदि URL को डाउनलोड करने के बाद यह अभी भी तो नहीं काम करता है यह शायद classpath के कारण. आप classpath में ड्राइवर जार फ़ाइल जोड़ने के लिए होगा.
)

 

import java.sql.*;
import javax.sql.*;

public class jdbcdemo{

public static void main(String args[]){
String dbtime;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";

try {

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while

con.close();
} //end try

catch(ClassNotFoundException e) {
e.printStackTrace();
}

catch(SQLException e) {
e.printStackTrace();
}

}  //end main

}  //end class

Sunday, August 12, 2012

dosti

Chand adhura hai sitaro ke bina,
Gulshan adhura hai baharuon ke bina,
Samundar adhura hai kinaro ke bina,
Jeena adhura hai tum jaise yaaro ke bina….




Kisi Ko Apni Khoobion Ka Ehsaas Nahin Hota,
Aap Jaisa Dostoon Ka Milna Itifaaq Nahin Hota,
Achha Kuch Kia HoGa Hum Ne,
Warna Aap Ho Sath Humaray Yeh Yaqeen Nahin Hota…




Kuch rishte uparwala banata hain,
Kuch rishte log banate hain,
Par kuch loog bina kisi rishte je hi rishte nibhate hain,
Shayad wohi dost sacche dost kehlate hain….




Sitam karo ya na karo, hum gila nahi karte,
Virano mein kabhi phool khila nahi karte,
Magar itna yaad rakhna mere yaar,
Hum jaise dost baar baar mila nahi karte…




Aapki dosti ko ehsaan maangte hai,
Nibhana apna imaan maangte hai,
Lekin ham wo nahi jo dosti me apni jaan de denge,
Kyonki dosto ko to ham apni jaan maante hai…





Kaho usi se jo na kahe kisi se!
Maango usi se jo dede khushi se !
Chaho use jo tumhe mile kismat se !
Dosti karo usi se jo hamesha nibhaye hasi se…




Dil ka rishta hai humara,
dil ke kone mein hai naam tumhara,
har yaad mein hai chehra tumhara,
saath nahin toh kya hua,
zindagi bar dosti nibhane ki waada hai humaara…

mescellaneous

Jab chla chor k batlane ki zehmat bhi na ki,
Khob tha dosti ek arsa nibhanay wala,
Dushmani k bhi tu aadaab hain aey dost bata,
Koi itna bhi na tha tujh ko batanay wala…





Pakar tumhe sapne sach lagne lage
ajnabi se the jo kabhi aaj apne lagne lage
hota nahin yakin khud ki kismat par
dhadkane hote bhi woh jaan lagne lage…
`
Taras gaye apke deedar ko
phir bhi dil aap hi ko yaad karta hai
humse khusnaseeb to apke ghar ka aaina hai
jo har roz apke husn ka deedar karta hai…
`
Saja kar apni hi aankh hazaar chehron pe
kiya hai maine sada aitbaar chehron pe
main teri bazm me kis – kis se dushmani leta
likha tha naam tera be-shumaar chehron pe…
`
Thi woh koi ladki ya thi woh koi bala
dil uski khoobsoorti mein toh hai bas dhala
kuch lamho ke deedar ke aage na ye dil chala
jaise hua koi jadoo ya dikhayi kisi ne kala…
`
Apke aane se khil gaya hai aangan
aapke saath se jhoom untha hai gagan
aap ho isiliye khush hai sara chaman
aur aapse pyar karne ko hum lenge hazaron janam…




Hey ishwar, aap to hain karunanidhan.
Jo jag mein rakhte hain sabkaa dhyaan.
Mere is hriday mein aap sadaa waas kijiye,
Banke mere shareer ke praan.
Aap meri jindagi mein khushiyon ki bahaar lekar aaye hain…



Tere gum mein tadap ke mar jayenge,
Mar gaye toh tera naam le jayenge,
Rub ko rishwat deke tujhe bhi bulayenge…
Jab tum uper aaoge toh…… saath beth ke KURKURE khayenge.




Kabhi saath chale nahin uske, lekin uske bina jeena mushkil hai
Uski zaroorath nahin hai, lekin uske bina zindagi adhoori hai
Aansun nahin bahaathe,  lekin uski yadonme dil rotha hai
Kya karun main,  mujhe kyun aisa ajeeb sa mehsoos hotha hai!!!




Ek Alag Si Pehchan Ban ne Ki Aadat Hai Ha
Zakhm H? Jitna Gehra Utna Muskurane Ki Aadat Hai
Sab Kùch Luta Deta Hai D?osti Me “Anjan”
Q K D?sti Nibhane Ki Adat Hai Hume



Mat karo pyar kisi se phoolon ki taraha,
Phool to pal mae Murjha jaate hai,
Pyar karo to karo Kaaton ki taraha,
Jo Chubhne ke baad bi Yaad Aate hain !!

Sher

Kabhi Maa Ko Na Dekhu To Chain Nahi Aata Hai,
Dil Na Jane Kyu Maa Ka Naam Sochte Hi Behel Jata Hai,
Kabhi Muskra De To Lagta Hai Zindgi Mil Gayi Mujhko Nayi,
Kabhi Dukhi Ho To Dil Mera Bhi Dukhi Ho Jata Hai…


Ek Hasti hai jo Jaan hai Meri,
Jo Aan se barh kar Maan hai Meri,
Khuda Hukum dai to kar don sajda usay,
Kyon k woh koi aur nahi Maa hai meri…



Akasr jab hum unko yaad karte hai….
Apne rab se yahi faryaad karte hai…
Umar hamari bhi lag jaye unko..
Kyoki hum unko khud se zyada pyar kaarte hai…


Yaadon Mein Har Pal Rahti Ho Tum,
Kabhi Na Dil Mein Khayaal Ho Tera Kam,
Tamanna Hai Yeh Dilki Mere,
Ki Tujhe Kabhi Chaahun Na Kam,
Bayaan Karun Jau Hai Dil Mein Mere,
Kahe Na Chaahen Hum,
Kahe Na Chaaho Tum,
Par Bayaan Karen Tau Hum Kaise Karen,
Dilse Hothon Tak Aaye Par,
Kahe Na Paayen Hum,Kahe Na Pao Tum…


Pehli baarish ka nasha hi kuchh alag hota hain,
Palko ko chhute hi sidha dil pe asar hota hain,
Mehka mehka saawan aaj iss dil ko behka raha hain,
Gumsum si nazro ko aaj ye pyar karna sikha raha hain …


Ae dost zindagi bhar mujhse dosti nibhaana,
dil ki koi bhi baat humse kabhi na chupaana,
sath chalna mere tum dukh sukh mein
bhatak jau mein jo kabhi sahi raasta dikhlaana…

Intajaar uska jiske aane ki koi aas ho,
Khushboo bhi us phool ki jo mere paas ho,
Manjil na mil saki hame to koi baat nahi,
Gam bhi usi shakhs ka hota hai jise pyaar ka ehsaas ho.

Dard Shayari

Gehri thi raat, lakin hum khoye nahi,
Dard bahoot tha dil mein, lakin hum roye nahi,
Koi nahi hamara jo puche humse,
Jag rahe ho kisi ke liye, ya kisi ke liye soye hi nahi..!!


Karta raha fareb koi saadgi ke saath,
Itna bada mazak meri zindagi ke saath,
Shyad mili saza iis jurm ki mujhe,
Ho gaya tha pyaar mujhe ek ajnaabi ke saath ….


Yeh Kaisi Judai Hai Jisne Hamein Shayar Bana Diya,
Yeh Kaisa Gam Hai Jisne Hamein Bebas Bana Diya,
Socha Nahi Tha Juda Ho Jaoge Humse Kabhi,
Karte Bhi Kya Jab Apne He Gair Bana Diya…


Aaj phir uski yaad ne rula diya,
kesha hain ye chera jisne ye sila diya,
do lafj likhne ka salika na tha,
uske pyar ne mujhe shayar bana diya….


Chaman Se Bichhda Hua Ek Gulab Hoon,
Main Khud Apni Tabaahi Ka Jawaab Hoon,
Yoon Nigaahein Na Fer Mujhse Mere Sanam,
Main Teri Chahaton Mein Hi Hua Barbaad Hoon. ..


Sagar se dosti to kinaare bhi nhi karte
Aajkat to wafa humse hamare bhi nhi karte
Ek tumse thi ummeed,
So wo bhi aaj toot gayi…
Chup-chap beh jaate hain,
Kisi se sikayat mere aansu bechaare nhi karte…..


Na ki maine jiski justuju na thi dil ko jiski arzoo
Kyun bana dard-e-dil uska rehna mere char soo…

Jo na tha naseeb main visal-e-yaar to kyun kiya mujhe bekrar
Kyun khuda hua meharban iskadar la ke usko mere ruu baruu…

Na thi jiski chamak fiza main na thi jiski mehak hawa main
Kyun wo bas gya mere rom rom main hoke mehw-e-guftgu…..

For True love


Door jakar bhi hum door jaa na sakenge,
Kitna royenge hum bata na sakenge,
Gham iska nahi ki aap mil na sakoge,
Dard is baat ka hoga ki hum aapko bhula na sakenge!

Pyar Ki Anokhi Murat Ho Tum,
Zindagi Ki Ek Zaruat Ho Tum,
Phool To Khoobsurat Hote Hi Hai,
Par Phoolo Se Bhi Khoobsurat Ho Tum.

Girti hui baarish ki bundon ko apne haton me samet lo,
jitna paani tum samet paye utna yaad tum humen karte ho,
jitna pani tum samet nahi paye, utna yaad hum tumhe karte hain..


Hum tanhaiyon se nahin,
Mehfil mehsion se dartein hain,
Hum zamane se nahin,
Apne aap se dartein hain,
Yun to bahut kuch khoya hai humne,
Par najane kyon aapko khone se dartein hai…

Gham Mein Hasne Walon Ko Rulaya Nahi Jata
Lehron Se Pani Ko Hataya Nahi Jata
Honay Wale Ho Jate Hain Khud He Apne
Kisi Ko Keh Kar Apna Banaya Nahi Jata…

Yaad rukti nahi rok paane se.
Dil maanta nahi kisi k smjhane se.
Ruk jati hai dhadkene aapko bhool jane se.
Isliye aapko yaad karte hai zine k bhane se..



Pal bhar mein tut jaye woh Kasam nahi,
Apko bhul jaye woh Hum nahi,
Tum hume bhul jao is baat me dum nahi,
kyonki Tum hume bhul jao itne bhi bure hum nahi…

Wednesday, August 8, 2012

Does God Answer Our Prayers?
       
What does it take for God to answer our prayer?

How to Pray: Prayers That Get Answered

What is prayer?



Have you ever known someone who really trusts God? When I was an atheist, I had a good friend who prayed often. She would tell me every week about something she was trusting God to take care of. And every week I would see God do something unusual to answer her prayer. Do you know how difficult it is for an atheist to observe this week after week? After a while, "coincidence" begins to sound like a very weak argument.

So why would God answer my friend's prayers? The biggest reason is that she had a relationship with God. She wanted to follow God. And she actually listened to what he said. In her mind, God had the right to direct her in life, and she welcomed him doing just that! When she prayed for things, it was a natural part of her relationship with God. She felt very comfortable coming to God with her needs, her concerns, and whatever issues were current in her life. Furthermore, she was convinced, from what she read in the Bible, that God wanted her to rely on him like that.

She pretty much exhibited what this statement from the Bible says, "This is the confidence we have in approaching God: that if we ask anything according to his will, he hears us."1 "For the eyes of the Lord are on the righteous and his ears are attentive to their prayer..."2
So, Why Doesn't God Answer Everyone's Prayers?

It may be because they don't have a relationship with God. They may know that God exists, and they might even worship God from time to time. But those who never seem to have their prayers answered probably don't have a relationship with him. Further, they have never received from God complete forgiveness for their sin. What does that have to do with it you ask? Here is an explanation. "Surely the arm of the Lord is not too short to save, nor his ear too dull to hear. But your iniquities have separated you from your God. Your sins have hidden his face from you, so that he will not hear."3

It's pretty natural to feel that separation from God. When people begin to ask God for something, what usually takes place? They begin with, "God, I really need your help with this problem..." And then there's a pause, followed by a restart... "I realize that I'm not a perfect person, that I actually have no right to ask you for this..." There's an awareness of personal sin and failure. And the person knows that it's not just them; that God is aware of it too. There's a feeling of, "Who am I kidding?" What they may not know is how they can receive God's forgiveness for all their sin. They might not know that they can come into a relationship with God so that God will hear them. This is the foundation for God answering your prayer.
How to Pray: The Foundation

You must first begin a relationship with God. Imagine some guy named Mike decides to ask the president of Princeton University (whom Mike doesn't even know) to co-sign a car loan for him. Mike would have zero chance of that happening. (We're assuming that the president of Princeton is not an idiot.) However, if that same president's daughter asked her dad to co-sign a car loan for her, it would be no problem. Relationship matters.

With God, when the person is actually a child of God, when the person belongs to God, he knows them and hears their prayers. Jesus said, "I am the good shepherd. I know my sheep and my sheep know me...my sheep listen to my voice. I know them and they follow me. I give them eternal life and they shall never perish; no one can snatch them out of my hand."4

When it comes to God then, do you really know him and does he know you? Do you have a relationship with him that warrants God answering your prayers? Or is God pretty distant, pretty much just a concept in your life? If God is distant, or you're not sure that you know God, here is how you can begin a relationship with him right now: Getting Connected.
Will God Definitely Answer Your Prayer?

For those who do know him and rely on him, Jesus seems to be wildly generous in his offer: "If you remain in me and my words remain in you, ask whatever you wish, and it will be given you."5 To "remain" in him and have his words remain in them means they conduct their lives aware of him, relying on him, listening to what he says. Then they're able to ask him whatever they want. Here is another qualifier: "This is the confidence we have in approaching God: that if we ask anything according to his will, he hears us. And if we know that he hears us -- whatever we ask -- we know that we have what we asked of him."6 God answers our prayers according to his will (and according to his wisdom, his love for us, his holiness, etc.).

Where we trip up is assuming we know God's will, because a certain thing makes sense to us! We assume that there is only one right "answer" to a specific prayer, assuming certainly THAT would be God's will. And this is where it gets tough. We live within the limits of time and limits of knowledge. We have only limited information about a situation and the implications of future action on that situation. God's understanding is unlimited. How an event plays out in the course of life or history is only something he knows. And he may have purposes far beyond what we could even imagine. So, God is not going to do something simply because we determine that it must be his will.
What Does It Take? What is God Inclined to Do?

Pages and pages could be filled about God's intentions toward us. The entire Bible is a description of the kind of relationship God wants us to experience with him and the kind of life he wants to give us. Here are just a few examples:

"...the Lord longs to be gracious to you. He rises to show you compassion. For the Lord is a God of justice. Blessed are all who wait for [trust] him!"7 Did you catch that? Like someone rising out of his chair to come to your help, "He rises to show you compassion." "As for God, his way is perfect...He is a shield for all who take refuge in him."8 "The Lord delights in those who fear [reverence] him, who put their hope in his unfailing love."9

However, God's greatest display of his love and commitment to you is this: Jesus said, "Greater love has no one than this, that he lay down his life for his friends,"10 which is what Jesus did for us. And so, "If God is for us, who can ever be against us? Since God did not spare even his own Son but gave him up for us all, won't God, who gave us Christ, also give us everything else?"11
What about "Unanswered" Prayer?

Certainly people get sick, even die; financial problems are real, and all sorts of very difficult situations can come up. What then?

God tells us to give our concerns to him. Even as the situation remains dismal, "Cast all your anxiety on him, because he cares for you."12 The circumstances may look out of control, but they aren't. When the whole world seems to be falling apart, God can keep us together. This is when a person can be very grateful that they know God. "The Lord is near. Be anxious for nothing, but in everything by prayer and supplication with thanksgiving let your requests be made known to God. And the peace of God, which surpasses all comprehension, will guard your hearts and your minds in Christ Jesus."13 God may provide solutions, resolutions to the problem WAY beyond what you imagined possible. Probably any Christian could list examples like this in their own lives. But if the circumstances do not improve, God can still give us his peace in the midst of it. Jesus said, "Peace I leave with you; my peace I give to you; not as the world gives do I give to you. Do not let your heart be troubled, nor let it be fearful."14

It is at this point (when circumstances are still tough) that God asks us to continue to trust him -- to "walk by faith, not by sight" the Bible says. But it's not blind faith. It is based on the very character of God. A car traveling on the Golden Gate Bridge is fully supported by the integrity of the bridge. It doesn't matter what the driver may be feeling, or thinking about, or discussing with someone in the passenger seat. What gets the car safely to the other side is the integrity of the bridge, which the driver was willing to trust.

In the same way, God asks us to trust his integrity, his character...his compassion, love, wisdom, righteousness on our behalf. He says, "I have loved you with an everlasting love, therefore I have continued my faithfulness to you."15 "Trust in him at all times, O people. Pour out your heart before him. God is a refuge for us."16
In Summary...How to Pray

God has offered to answer the prayers of his children (those who have received him into their lives and seek to follow him). He asks us to take any concerns to him in prayer and he will act upon it according to his will. As we deal with difficulties we are to cast our cares on him and receive from him a peace that defies the circumstances. The basis for our hope and faith is the character of God himself. The better we know him, the more apt we are to trust him.

For more on the character of God, please see "Who is God?" or other articles on this site. The reason for our prayers is God's character. The first prayer God answers is your prayer to begin a relationship with God.