ResultSetMetaData.getMetaData() का उपयोग करें
JDBC में ResultSet से कॉलम नाम प्राप्त करने के लिए getMetaData() मेथड को कॉल करें जो ResultSetMetaData ऑब्जेक्ट लौटाता है।
प्रोटोटाइप
ResultSetMetaData getMetaData() throws SQLException;
मुख्य मेथड्स
getColumnCount()— कॉलम की संख्या।getColumnLabel(int column)— कॉलम लेबल/उपनाम (1-आधारित इंडेक्स)।getColumnName(int column)— मूल कॉलम नाम।getColumnType(int column)— SQL प्रकार कोड।
टेस्ट टेबल बनाना
mysql> CREATE TABLE javagetallcolumnnames (
Id INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(20),
Age INT,
Salary FLOAT,
Address VARCHAR(100),
PRIMARY KEY(Id)
);
पूर्ण Java कोड
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 = null;
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();
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {}
try { if (stmt != null) stmt.close(); } catch (Exception e) {}
try { if (con != null) con.close(); } catch (Exception e) {}
}
}
}
आउटपुट
The column names are as follows: Id Name Age Salary Address
कोड स्क्रीनशॉट

महत्वपूर्ण नोट्स
- कॉलम इंडेक्स 1-आधारित हैं (0 नहीं)।
getColumnLabel()उपनाम लौटाता है यदिAS aliasउपयोग किया गया हो; अन्यथा कॉलम नाम।- हमेशा
finallyब्लॉक में संसाधन बंद करें (या try-with-resources उपयोग करें)। - MySQL Connector/J 8.0+ में
com.mysql.cj.jdbcपैकेज उपयोग करें।
Maven निर्भरता
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>