Connect to Database using JDBC

290 Flares Twitter 0 Facebook 0 Google+ 290 LinkedIn 0 290 Flares ×

Connecting to the Database is the hello world example for learning JDBC. In JDBC, the client  ( java program) connects to the data source using the JDBC driver for the particular database. The driver is the program responsible for handling all communications with the underlying data source. The data source typically resides on another machine in the network and the network communication is also handled by the JDBC driver.


For this tutorial we use MYSQL Database and assuming that you already have installed MYSQL in the local machine, if not please install MYSQL

Setting up the environment

First thing is you need to install Java (JDK). Download JDK

Next step is to download the MYSQL JDBC Driver and add it the classpath. You can get it from   Download MySQL JDBC Driver

The JDBC drivers are of 4 types. They are

Type 1 
Relies on another data access API, such as ODBC (Open Database Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge is an example of a Type 1 driver.

Type 2
Drivers that are written partly in the Java programming language and partly in native code.  Due to native code portability is limited

Type 3
Drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client’s requests to the data source.

Type 4
These are pure java drivers and they implement the network protocol for a particular data source.

The MySQL Driver we use for this example is a Type 4 JDBC driver.

Connecting to MYSQL Database

The above code is core of  establishing the connection. Remember to close the connection after use.  The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. Make sure to change the hostname , port, dbname ( schema) , user and password to the appropriate values for your DB.

Example Java Code