如何使用 JDBC 从 ResultSet 中获取所有列名
可以通过 ResultSetMetadata 接口的 getColumnName() 方法来获取特定列的名称。
此方法接受一个表示列索引的整数值,并返回一个表示指定列名称的字符串值。
我们使用 CREATE 语句在 MySQL 数据库中创建一个名为MyPlayers 的表,如下所示 −
CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );
现在,我们将使用 INSERT 语句在MyPlayers 表中插入 7 条记录 −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
下面的 JDBC 程序与数据库建立连接,将名为 MyPlayers 的表的内容检索到 ResultSet 对象中,使用 getColumnName() 方法获取表的列名并显示出来。
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; public class RS_AllColumnNames { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from MyPlayers"); //Retrieving the ResultSetMetadata object ResultSetMetaData rsMetaData = rs.getMetaData(); System.out.println("List of column names in the current table: "); //Retrieving the list of column names int count = rsMetaData.getColumnCount(); for(int i = 1; i<=count; i++) { System.out.println(rsMetaData.getColumnName(i)); } } }
输出
Connection established...... List of column names in the current table: ID First_Name Last_Name Date_Of_Birth Place_Of_Birth Country
广告