Programmer Coding

Connceting to DB

What is JDBCDriver?

 

JDBC drivers implement the circle borderlines in the JDBC API, for interacting with your   database (collection of information)  server.

For example, using JDBC drivers enable you to open database (collection of information)  connections and to interact with it by sending SQL or database (collection of information)  commands then receiving results with Java.

 

The Java.sql package that ships with JDK, insure  various classes with their behaviours circle and their actual implementaions are done in third-party drivers. Third party distributors applies the java.sql.Driver borderline in their database (collection of information)  driver.

JDBC Drivers Types

JDBC driver fulfilments vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the fulfilment types into four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBCBridge Driver

In a Type 1 driver, a JDBC bridge is used to entrance ODBC drivers installed on each client machine. Using ODBC, needs configuring on your system a Data Source Name (DSN) that represents the target database (collection of information) .

When Java first came out, this was a useful driver because most database (collection of information) s only accepted ODBC entrance but now this type of driver is recommended only for experimental use or when no other alternative is free-for-all.

 

 

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database (collection of information) . These drivers are typically provided by the database (collection of information)  distributors and used in the same manner as the JDBC-ODBC Bridge. The distributor-specific driver must be installed on each client machine.

 

If we change the Database (collection of information) , we have to change the native API, as it is specific to a database (collection of information)  and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC’s overhead.

The Oracle Call Borderline (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to entrance database (collection of information) s. The JDBC clients use typical network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format needd by the DBMS, and forwarded to the database (collection of information)  server.

This kind of driver is extremely changeability , since it needs no code installed on the client and a single driver can actually provide entrance to multiple database (collection of information) s.

 

You can think of the application server as a JDBC “proxy,” meaning that it makes calls for the client application. As a result, you need some knowledge of the application server’s configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database (collection of information) , understanding the nuances will prove helpful.

Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the distributor’s database (collection of information)  through socket connection. This is the highest applyance driver free-for-all for the database (collection of information)  and is usually provided by the distributor alone.

This kind of driver is extremely changeability , you don’t need to install specific software on the client or server. Further, these drivers can be downloaded dynamically.

MySQL’s Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database (collection of information)  distributors usually supply type 4 drivers.

Which Driver should be Used?

If you are entranceing one type of database (collection of information) , such as Oracle, Sybase, or IBM, the preferred driver type is 4.

If your Java application is entranceing multiple types of database (collection of information) s at the same time, type 3 is the preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not free-for-all yet for your database (collection of information) .

 

The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.

Example to connect to the mysql database (collection of information)  in java

 

For connecting java application with the mysql database (collection of information) , you need to follow 5 steps to apply                           database (collection of information)  connectivity.

 

In this example we are using MySql as the database (collection of information) . So we need to know following informations  for the mysql database (collection of information) :

 

  1. Driver class: The driver class for the mysql database (collection of information) is mysql.jdbc.Driver.
  2. Connection  URL: The      connection      URL      for      the       mysql       database (collection of information)  is jdbc:mysql://localhost:3308/sono where jdbc is the API, mysql is the database (collection of information) , localhost is the server name on which mysql is running, we may also use IP address, 3308 is the port number and sono is the database (collection of information)   We may use any database (collection of information) , in such case, you need to replace the sonoo with your database (collection of information)  name.
  3. Username: The default username for the mysql database (collection of information) is root.
  4. Password: Password is given by the user at the time of installing the mysql database (collection of information) . In this example, we are going to use root as the

 

Let’s first produce a table in the mysql database (collection of information) , but before creating table, we need to produce  database (collection of information)  first.

 

  1. produce database (collection of information) sono;
  2. use sono;
  3. produce table emp(id int(10),name varchar(40),age int(3)); Example to Connect Java Application with mysql database (collection of information)

In this example, sonoo is the database (collection of information)  name, root is the username and password.

 

import java.sql.*;

class MysqlCon{

public static void main(String args[]){ try{ Class.forName(“com.mysql.jdbc.Driver”);

Connection con=DriverManager.getConnection( “jdbc:mysql://localhost:3308/sono”,”root”,”root”);

//here sonoo is database (collection of information)  name, root is username and password

 

Statement stmt=con.produceStatement();

ResultSet rs=stmt.applyQuery(“select * from emp”);

while(rs.next())

System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+rs.getString(3)); con.close();

}catch(Exception e){ System.out.println(e);}

} }

 

The above example will fetch all the records of emp table.

 

To connect java application with the mysql database (collection of information)  mysqlconnector.jar file is needd to be loaded.

Two way(method) s to load the jar file:

  1. paste the mysqlconnector.jar file in jre/lib/ext folder
  2. set classpath

 

1)    paste the mysqlconnector.jar file in JRE/lib/ext folder:

Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

 

2)    set classpath:

There are two way(method) s to set the classpath: 1.temporary 2.permanent

How to set the temporary classpath

open command prompt and write:

  1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

 

How to set the permanent classpath

 

Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;

 

JDBC-Result Sets

The SQL statements that read data from a database (collection of information)  query, return the data in a result set. The SELECT statement is the typical way(method)  to select rows from a database (collection of information)  and view them in a result set. The java.sql.ResultSet borderline represents the result set of a database (collection of information)  query.

 

 

Type of ResultSet

The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY.

Type Description
ResultSet.TYPE_FORWARD_ONLY The cursorily can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursorily can scroll forward and backward, and the result set is not sensitive to changes made by others to the database (collection of information)  that happen after the result set was produced.

 

ResultSet.TYPE_SCROLL_SENSITIVE. The cursorily can scroll forward and backward, and the result set is sensitive to changes made by others to the database (collection of information)  that happen after the result set was produced.

Concurrencyof ResultSet

The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description
ResultSet.CONCUR_READ_ONLY Produces a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Produces an updateable result set.

 

Viewinga Result Set

The ResultSet borderline insure  dozens of way(method) s for getting the data of the current row. There is a get way(method)  for each of the possible data types, and each get way(method)  has two versions

  • One that takes in a column

 

  • One that takes in a column

 

For example, if the column you are interested in viewing insure  an int, you need to use one of the getInt() way(method) s of ResultSet −

S.N. Way(method) s & Description
1 public int getInt(String columnName) throws SQLException

 

Returns the int in the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLException

Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.

 

Similarly, there are get way(method) s in the ResultSet borderline for each of the eight Java primitive types, as well as frequent types such as java.lang.String, java.lang.Object, and java.net.URL.

There are also way(method) s for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL data types.

For a best understanding, let us study Viewing – Example Code. Updating a Result Set

The ResultSet borderline insure  a set of update way(method) s for updating the data of a result

set.

 

As with the get way(method) s, there are two update way(method) s for each data type −

 

  • One that takes in a column

 

  • One that takes in a column

 

For example, to update a String column of the current row of a result set, you would use one of the following updateString() way(method) s −

S.N. Way(method) s & Description
1 public void updateString(int columnIndex, String s) throws SQLException

 

Changes the String in the specified column to the value of s.

2 public void updateString(String columnName, String s) throws SQLException Similar to the previous way(method) , except that the column is specified by its name instead of its index.

There are update way(method) s for the eight primitive data types, as well as String, Object, URL, and  the SQL data types in the java.sql package.

Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the basic database (collection of information) . To update your changes to the row in the database (collection of information) , you need to produce one of the following way(method) s.

S.N. Way(method) s & Description
1 public void updateRow()

 

Updates the current row by updating the corresponding row in the database (collection of information) .

2 public void deleteRow()

Deletes the current row from the database (collection of information)

3 public void refreshRow()

Refreshes the data in the result set to reflect any recent changes in the database (collection of information) .

4 public void cancelRowUpdates()

Cancels any updates made on the current row.

5 public void insertRow()

Inserts a row into the database (collection of information) . This way(method)  can only be produce when the cursorily is                                   pointing to the insert row.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top