Unit V_interacting-with-database
Unit V_interacting-with-database
ODBC
public static void registerDriver(Driver driver); is used to register the given driver
with DriverManager.
• Driver Interface
This interface handles the communications
with the database server. You will very rarely
interact directly with Driver objects. Instead,
you use DriverManager objects, which
manages objects of this type. It also abstracts
the details associated with working with
Driver objects.
Common JDBC Components (cont’d..)
• Connection Interface
A Connection is the session between java
application and database. The Connection
interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData.
The Connection interface provide many
methods for transaction management like
commit(),rollback() etc.
Commonly used methods of Connection interface
Method Description
• Statement Interface
The Statement interface provides methods to
execute queries with the database. It provides
factory method to get the object of ResultSet.
Commonly used methods of Statement interface
Method Description
public boolean execute(String sql); used to execute queries that may return
multiple results.
• ResultSet Interface
Creating Connection
Creating Statement
Execute Query
Close Connection
Connecting to Database
• There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2. Creating connection
• The DriverManager .getConnection() method is used
to establish connection with the database.
database. This method returns the object of ResultSet that can be used to get all the records
of a table.
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5. Closing connection
con.close();
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/sun","root","root");
//here sun is database name, root is username and password
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);
}
}