Open In App

How to Use Methods of Column to Count Number of Columns in JDBC?

Last Updated : 07 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A single standalone program cannot be able to fulfill all the demands of the clients every request of the client has some different requests like the update, delete, insertJDBC is one of the famous API of the java language that is used to connect relational databases working on the Structured Query Language with the java programs.JDBC along with the database driver is capable of accessing databases and spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the help of JDBC APIs.

The main tasks of the JDBC API

  1. Establish a connection with a database
  2. Send SQL statements to the database server.
  3. Process the result obtained.

Illustration: Suppose MySQL Client

Input : 

  • Database : GFG
  • Table : Aayush

Output : 

Approach: Steps for connectivity between Java program and database

  1. Importing the database files.
  2. Load and register drivers to java program.
  3. Establish the connections.
  4. Create a statement.
  5. Execute the query.
  6. Process the results.
  7. Close the connections.

Now, discussing the above steps in order figuring out how to use methods of the column to count no of columns in JDBC

1. Loading and registering drivers: To begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of the two ways is by using Class.forName() method. It is used to load the driver’s class file into memory at the runtime and there is no need of using new or creation of an object. In order to illustrate for Oracle driver it is as follows:

 Class.forName(“oracle.jdbc.driver.OracleDriver”);

2. Establish the connections: After loading the driver, establish connections by creating an object of Connection class of main class as depicted:

Connection con = DriverManager.getConnection(url,user,password)
  • user: username from which your SQL command prompt can be accessed.
  • password: password from which your SQL command prompt can be accessed.
  • con: Connection class object is a reference to the Connection interface.
  • URL: Uniform Resource Locator.

If Oracle is used as a database then it is treated in a similar manner but with a little gimmick to it as follows. 

  • The driver used @localhost is the IP address where the database is stored.
  • 1521 is the port number.
  • The service provider is ‘xe’ here.

All 3 parameters here are of String type and are to be declared by the programmer before calling the function and using this can be referred from the final code. It can be created as follows:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”
OR
String mysqlUrl = "jdbc:mysql://localhost/Databasename";

3. Create a statement: Once a connection is established you can interact with the database. The JDBCStatement, Callable Statement and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows. Here, the con is a reference to the Connection interface used in the previous step.

Statement st = con.createStatement();

4. Execute the query: Now comes the most important part i.e executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows:

  • The query for updating/inserting table in a database.
  • The query for retrieving data.

The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table. The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting.

Example

Java




// Java Program to use methods of column
// to Count no of columns in JDBC
  
// Importing all classes of java.util package
import java.util.*;
  
// Step 1: Importing DB
import java.sql.*;
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
        throws ClassNotFoundException, SQLException
    {
        // Step 2: Loading and registering drivers
  
        // Registering using Drivermanager
        DriverManager.registerDriver(
            new com.mysql.jdbc.Driver());
  
        // MySQL URL
        String mysqlUrl = "jdbc:mysql://localhost/gfg";
  
        // Step 3: Establish the connection
        Connection con = DriverManager.getConnection(
            mysqlUrl, "root", "Aayush");
        // Display message to show in console
        // connection is estalished
        System.out.println("Connection established......");
  
        // Step 4: Creating a statement object
        Statement stmt = con.createStatement();
  
        // Step 5: Executing the query
        ResultSet rs
            = stmt.executeQuery("select * from aayush;");
  
        // Step 6: Process the results
  
        // Retrieving the ResultSetMetaData object
        ResultSetMetaData rsmd = rs.getMetaData();
  
        // Get the column type and count
        // using getColumnCount() method
        int column_count = rsmd.getColumnCount();
  
        // Print the number of columns in a table
        System.out.println(
            "Number of columns in the table : "
            + column_count);
    }
}


Output: 

Same table is used in the implementation part. So, the above output is of corresponding table generated below on which count is called. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads