Introduction to Java JDBC
Overview
This artical will be a brief explanation about JDBC which is an API for connecting and executing queries on a database.
JDBC stands for Java Database Connectivity. It is a specification from Sun Microsystems with a standard abstraction.
What is JDBC?
Mainly, JDBC is an API (Application Programming Interface) that can be used to connect Java applications to various databases. It is a Java API that accesses the data from various kinds of Relational databases. JDBC can work with any database as long as proper drivers are provided.
Why Should We Use JDBC?
Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:
⦁ Connect to the database
⦁ Execute queries and update statements to the database
⦁ Retrieve the result received from the database.
What do we need in order to use JDBC?
JDBC can be used with any database as long as we have proper set up for the samw. we certainly need the softwares mentioned below.
⦁ Java : Any version can be used. You can download from this link: https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html
⦁ Database: You can choose any data base like MySQL, Oracle etc.
⦁ Drivers: You will need the drivers according to the data base you have selected.
Database Connectivity:
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
⦁ Register the Driver class : We can use the forName() method of Class class to register the driver class. This method is used to dynamically load the driver class.
Syntax: public static void forName(String className)throws ClassNotFoundException
⦁ Create connection:The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax: 1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)throws SQLException
⦁ Create statement Object: To create a statement object we can use the createStatement() method.
Syntax: public Statement createStatement()throws SQLException
⦁ Execute queries: The executeQuery() method of Statement interface is used to execute queries to the database.
Syntax: public ResultSet executeQuery(String sql)throws SQLException
⦁ Close connection: The close() method of Connection interface is used to close the connection.
Syntax: public void close()throws SQLException
Comentários