import java.sql.*; public class ResultSetMetadataExample { public static void main(String[] args) { // Database URL and credentials String dbUrl = "jdbc:mysql://localhost:3306/nehal"; String user = "root"; String password = "nehal@123"; // SQL query String sql = "SELECT id, name FROM emp"; try (Connection conn = DriverManager.getConnection(dbUrl, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { // Get the ResultSetMetaData ResultSetMetaData rsMetaData = rs.getMetaData(); // Get the number of columns in the result set int columnCount = rsMetaData.getColumnCount(); System.out.println("Number of Columns: " + columnCount); // Print column names and types for (int i = 1; i <= columnCount; i++) { String columnName = rsMetaData.getColumnName(i); String columnType = rsMetaData.getColumnTypeName(i); System.out.println("Column " + i + ": " + columnName + " (" + columnType + ")"); } // Iterate through the result set and print data while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter