0% found this document useful (0 votes)
23 views

JavaJDBC 2

The 5 steps to connect a Java application to a database using JDBC are: 1) Register the driver class 2) Create a connection 3) Create a statement 4) Execute queries 5) Close the connection

Uploaded by

ujjawalr9027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

JavaJDBC 2

The 5 steps to connect a Java application to a database using JDBC are: 1) Register the driver class 2) Create a connection 3) Create a statement 4) Execute queries 5) Close the connection

Uploaded by

ujjawalr9027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Java Database Connectivity with 5

Steps
• There are 5 steps to connect any java
application with the database using JDBC.
• These steps are as follows:
– Register the Driver class
– Create connection
– Create statement
– Execute queries
– Close connection
1) Register the driver class
• The forName() method of Class class is used
to register the driver class. This method is
used to dynamically load the driver
class.Syntax of forName() method
– public static void forName(String className)throws Class
NotFoundException
• Here, Java program is loading oracle driver to
esteblish database connection.
– Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of DriverManager class is
used to establish connection with the database.
• Syntax of getConnection() method :-

• 1) public static Connection getConnection(String url)throws


SQLException

• 2) public static Connection getConnection(String url,String


name,String password) throws SQLException

• Example to establish connection with the Oracle database


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
• The createStatement() method of Connection
interface is used to create statement. The
object of statement is responsible to execute
queries with the database.Syntax of
createStatement() method
– public Statement createStatement()throws SQLException

• Example to create the statement object


– Statement stmt=con.createStatement();
4) Execute the query
• The executeQuery() method of Statement interface is used
to execute queries to the database. This method returns
the object of ResultSet that can be used to get all the
records of a table. Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query:-

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
• By closing connection object statement and
ResultSet will be closed automatically. The
close() method of Connection interface is used
to close the connection. Syntax of close()
method :-
public void close()throws SQLException
Example to close connection :-
con.close();
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to
follow 5 following steps.
• In this example we are using MySql as the database. So we need to
know following informations for the mysql database:

– Driver class: The driver class for the mysql database


is com.mysql.jdbc.Driver.
– Connection URL: The connection URL for the mysql database
isjdbc:mysql://localhost:3306/sample where jdbc is the API, mysql is
the database, localhost is the server name on which mysql is running,
we may also use IP address, 3306 is the port number and sonoo is the
database name. We may use any database, in such case, we need to
replace the sample with our database name.
– Username: The default username for the mysql database is root.
– Password: It is the password given by the user at the time of installing
the mysql database. In this example, we are going to use root as the
password.
• create database sample;
• use sample;
• create table emp(id int(10),name varchar(40),
age int(3));
Example to Connect Java Application with mysql database
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:3306/sample","root","root");
//here sample is database name, root is username and pa
ssword
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("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);}
}
}
• To connect java application with the mysql database, mysqlconnector.jar file is
required to be loaded.
• download the jar file mysql-connector.jar
• Two ways to load the jar file:
– Paste the mysqlconnector.jar file in jre/lib/ext folder
– 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 ways to set the classpath:


– temporary
– permanent
• How to set the temporary classpath
– open command prompt and write:
– 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;.;
For executing :
• java -cp .;mysql-connector-java-5.1.18-bin.jar
MysqlCon
DriverManager class
• The DriverManager class acts as an interface
between user and drivers. It keeps track of the
drivers that are available and handles establishing
a connection between a database and the
appropriate driver. The DriverManager class
maintains a list of Driver classes that have
registered themselves by calling the method
DriverManager.registerDriver().
• Method :-
– public static Connection getConnection(String url,String
userName,String password)
• is used to establish the connection with the specified url,
username and password.
Connection interface
• A Connection is the session between java
application and database. The Connection
interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData
i.e. object of Connection can be used to get
the object of Statement and
DatabaseMetaData. The Connection interface
provide many methods for transaction
management like commit(), rollback() etc.
• 1) public Statement createStatement(): creates a
statement object that can be used to execute SQL
queries.
• 2) public Statement createStatement(int
resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects
with the given type and concurrency.
• 3) public void setAutoCommit(boolean status): is used
to set the commit status.By default it is true.
• 4) public void commit(): saves the changes made since
the previous commit/rollback permanent.
• 5) public void rollback(): Drops all changes made since
the previous commit/rollback.
• 6) public void close(): closes the connection and
Releases a JDBC resources immediately.
• Statement interface
• The Statement interface provides methods to execute
queries with the database. The statement interface is a
factory of ResultSet i.e. it provides factory method to get
the object of ResultSet.
• Commonly used methods of Statement interface:
• The important methods of Statement interface are as
follows:
• 1) public ResultSet executeQuery(String sql): is used to
execute SELECT query. It returns the object of ResultSet.2)
public int executeUpdate(String sql): is used to execute
specified query, it may be create, drop, insert, update,
delete etc.3) public boolean execute(String sql): is used to
execute queries that may return multiple results.4) public
int[] executeBatch(): is used to execute batch of
commands.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@loc
alhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


//int result=stmt.executeUpdate("update emp765 set name=‘Harry',sa
lary=10000 where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}
}
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row of a table.
Initially, cursor points to before the first row.
• Methods :-
1) public boolean next():is used to move the cursor to the one row next from
the current position.
2) public boolean previous():is used to move the cursor to the one row
previous from the current position.
3) public boolean first():is used to move the cursor to the first row in result
set object.
4) public boolean last():is used to move the cursor to the last row in result set
object.
5) public int getInt(int columnIndex):is used to return the data of specified
column index of the current row as int.
6) public int getInt(String columnName):is used to return the data of
specified column name of the current row as int.
7) public String getString(int columnIndex):is used to return the data of
specified column index of the current row as String.
8) public String getString(String columnName):is used to return the data of
specified column name of the current row as String.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Res
ultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}
PreparedStatement interface
• The PreparedStatement interface is a
subinterface of Statement. It is used to
execute parameterized query.
• Let's see the example of parameterized query:
• String sql="insert into emp values(?,?,?)";
• As you can see, we are passing parameter (?)
for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Methods :-
• public void setInt(int paramIndex, int value)
– sets the integer value to the given parameter index.
• public void setString(int paramIndex, String value)
– sets the String value to the given parameter index.
• public void setFloat(int paramIndex, float value)
– sets the float value to the given parameter index.
• public void setDouble(int paramIndex, double value)
– sets the double value to the given parameter index.
• public int executeUpdate()
– executes the query. It is used for create, drop, insert,
update, delete etc.
• public ResultSet executeQuery()
– executes the select query. It returns an instance of
ResultSet.

You might also like