📜  Java ResultSetMetaData接口

📅  最后修改于: 2020-10-13 01:25:05             🧑  作者: Mango

Java ResultSetMetaData接口

元数据表示有关数据的数据,即我们可以从数据中获取更多信息。

如果必须获取表的元数据(例如列总数,列名,列类型等),则ResultSetMetaData接口很有用,因为它提供了从ResultSet对象获取元数据的方法。

ResultSetMetaData接口的常用方法

Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object.
public String getColumnName(int index)throws SQLException it returns the column name of the specified column index.
public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index.
public String getTableName(int index)throws SQLException it returns the table name for the specified column index.

如何获取ResultSetMetaData的对象:

ResultSet接口的getMetaData()方法返回ResultSetMetaData的对象。句法:


public ResultSetMetaData getMetaData()throws SQLException

ResultSetMetaData接口的示例:

import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
       Column Name of 1st column: ID
       Column Type Name of 1st column: NUMBER