Wednesday, August 7, 2013

What is JDBC and what are the steps to connect from java to any database ?

What is JDBC ?

JDBC is an API developed by Sun microsystems.

When you want to connect to database from java, we use JDBC api. JDBC is an API developed by Sun microsystems.Every database vendor(oracle or mysql) implements those api in a form of jar file.(Suppose ojdbc.jar contains classes which implement interfaces in JDBC api ,mysql.jar contains classes which implement interfaces in JDBC api). So to connect to database we need the jar file to connect to database.. because that jar files contains alll implementation classes of JDBC api. Examples of JDBC api are java.sql.connection,java.sql.ResultSet )

These are the following steps:

1)Load the driver(Load and register the driver by using class.forName())
(The argument to class.forName varies depending on the database you
like to connect)

Class.forName("oracle.jdbc.driver.OracleDriver");-- For Oracle.
oracle.jdbc.driver.OracleDriver is in ojdbc.jar file.

Class.forName("com.mysql.jdbc.Driver");-- For Mysql
com.mysql.jdbc.Driver is in mysql***.jar file.

Driver maps the JDBC calls to database calls..driver is like
mediator between JDBC and Database.

2)Define the Connection URL

Arguments to DriverManager.getConnection is the connection url.

My oracle is running at 1521 port. XE is database name.Next
2 arguments are database username and password.If you
are succesful up to this step you are ready to execute queries
on database.

connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE", "hr",
"hr");

3)Establish the Connection
connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE", "hr",
"hr");

4)Create a Statement Object

st = con.prepareStatement(sql);

5)Execute a Query

ResultSet rs = st.executeQuery();

6)Process the results

if(rs.next()){

7)close the Connection

You have to close the connection in finally block,connections will
get exhausted.. and we can't connect to database.

No comments:

Post a Comment