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

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

WBOY
Release: 2023-08-29 16:17:07
forward
1437 people have browsed it

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;
Copy after login

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)
Copy after login

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();
      }
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template