要获得结果集中的列名,您需要使用getMetaData()方法。getMetadata()的原型如下 −
ResultSetMetaData getMetaData throws SQLException;
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)
以下是获取ResultSet中列名的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;
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();
}
}
}
Here is the snapshot of the code −
The following is the output −
The column names are as follows:
Id
Name
Age
Salary
Address
这是示例输出的快照 −