Explain how Java interacts with database.

Explain how Java interacts with database. Give an example to explain it.

Java interacts with database using an API called Java Database Connectivity. JDBC is used to connect to the database, regardless the name of the database management software. Hence , we can say the JDBC is a cross-platform API.

The database is connected with a driver as long as the operations perform with a database manager.

Example:
Class.forName(DRIVER).newInstance(); // registers the driver
Connection con = DriverManager.getConnection("jdbc:mysql://db_lhost:3306/", "contacts",username,password);//establishes the connection to the database manager
Statement stmt = con.createStatement();
ResultSet resSet = stmt.executeQuery(“select * from emp);
The above code snippet establishes the connection to the database manager and retrieve tuples.

How Java interacts with database?

Java uses the JDBC (Java Database Connectivity) which is a programming framework to let the communication between the database and the programs.

Example
try
{
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con=DriverManager.getConnection("jdbc:odbc:MyDSN","scott","tiger");
   PreparedStatement stmt=con.prepareStatement("insert into StudentTBL values(?,?,?)");
   stmt.setInt(1,13);
   stmt.setString(2,"Rob");
   stmt.setInt(3,26);
   int rows=stmt.executeUpdate();
   System.out.println(rows+" rows inserted");
}
catch(ClassNotFoundException ce)
{
   ce.printStackTrace();
}
catch(SQLException se)
{
   se.printStackTrace();
}
}
How can we handle SQL exception in Java?
SQL Exception is associated with a failure of a SQL statement. This exception can be handled like an ordinary exception in a catch block...
What is DatabaseMetaData in Java?
DatabaseMetaData provides comprehensive information about the database...
What is ResultSetMetaData in Java?
ResultSetMetaData is a class which provides information about a result set that is returned by an executeQuery() method...
Post your comment