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.

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.

   Connection con=DriverManager.getConnection("jdbc:odbc:MyDSN","scott","tiger");
   PreparedStatement stmt=con.prepareStatement("insert into StudentTBL values(?,?,?)");
   int rows=stmt.executeUpdate();
   System.out.println(rows+" rows inserted");
catch(ClassNotFoundException ce)
catch(SQLException se)
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