Home  >  Article  >  Database  >  How to get column names on ResultSet in Java using MySQL?

How to get column names on ResultSet in Java using MySQL?

WBOY
WBOYforward
2023-08-29 16:17:071359browse

To get the column names in the result set, you need to use the getMetaData() method. The prototype of getMetadata() is as follows −

ResultSetMetaData getMetaData throws SQLException;

Create a MySQL table with 5 column names. The query to create a table is as follows −

mysql> create table javagetallcolumnnames
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Salary float,
   -> Address varchar(100),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.34 sec)

The following is the Java code to get the column names in ResultSet . The code is as follows −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class GetAllColumnNames {
   public static void main(String[] args) {
      String JdbcURL="jdbc:mysql://localhost:3306/test?useSSL=false";
      String Username="root";
      String password="123456";
      Connection con=null;
      Statement stmt=null;
      ResultSet rs;
      try {
         con = DriverManager.getConnection(JdbcURL, Username, password);
         stmt=con.createStatement();
         rs = stmt.executeQuery("SELECT *FROM javagetallcolumnnames");
         ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
         int counter = md.getColumnCount();
         String colName[] = new String[counter];
         System.out.println("The column names are as follows:");
         for (int loop = 1; loop <= counter; loop++) {
            colName[loop-1] = md.getColumnLabel(loop);
            System.out.println(colName[loop-1]);
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Here is the snapshot of the code −

如何使用 MySQL 在 Java 中获取 ResultSet 上的列名称?

The following is the output −

The column names are as follows:
Id
Name
Age
Salary
Address

This is the sample output Snapshot of −

如何使用 MySQL 在 Java 中获取 ResultSet 上的列名称?

The above is the detailed content of How to get column names on ResultSet in Java using MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete