Can you explain how Java interacts with database?

Can you explain how Java interacts with database?

Java interacts with database with the help of JDBC means Java Database Connectivity. It is an API for the Java Programming Language that defines how a client may access a database. It provides method for querying and updating data in database. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment. JDBC classes are in the java.sql package. For JDBC connectivity, firstly the JDBC-ODBC driver is registered then by using DriverManagerClass the connection is established. This class throws sqlException hence it must be caught. The Driver is used to resolve type compatibility issues between Java application and different database servers like Oracle, Access, and SQL Server.

Example of connectivity with SQL Server
import java.io.*;

import java.sql.*;

import java.util.*;

class dri

{

   public static void main(String x[])

   {

       try

       {

           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

           System.out.println("Driver registered with the driver manager class");

           Connection con = DriverManager.getConnection("jdbc:odbc:students");//database connection

           System.out.println("connected");

           BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

           System.out.println("Enter Roll no");

           int a=Integer.parseInt(br.readLine());

           System.out.println("Enter name");

           String b=br.readLine();

           System.out.println("Enter branch");

           String c=br.readLine();

           System.out.println("Enter Marks");

           int d=Integer.parseInt(br.readLine());

           //query for inserting values in the table

           PreparedStatement p=con.prepareCall("insert into stud values(?,?,?,?)");

           p.setInt(1,a);

           p.setString(2,b);

           p.setString(3,c);

           p.setInt(4,d);

           p.executeUpdate();

           System.out.println("Record inserted")

       }

       catch(Exception e)

       {

           System.out.println(e);

       }

   }

}
Different section of JDBC and their usage.
Different section of JDBC and their usage. - JDBC Driver Manager, which communicates with vendor-specific drivers that perform the real communication with the database...
Can you explain SQLException class? What is SQL State in SQL Exception
SQLException class - The SQLException Class and its subtypes provide information about errors and warnings that occurs when the data source is accessed...
CallableStatement interface
CallableStatement interface - It is an interface which is the sub interface of Statement Interface....
Post your comment